Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理

1.创建项目

Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第1张图片
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第2张图片
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第3张图片
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第4张图片

2.数据库创建

CREATE DATABASE wechat_demo;
use wechat_demo;

/*创建表*/
CREATE table `wechat_area`(
`area_id` INT(2) NOT NULL auto_increment COMMENT '地区ID',
`area_name` VARCHAR(200) NOT NULL COMMENT '地区名',
`priority` INT(2) NOT NULL DEFAULT '0' COMMENT '显示的优先级',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`last_edit_time` datetime DEFAULT NULL COMMENT '最后的修改时间',
PRIMARY KEY(`area_id`),
UNIQUE KEY `UK_AREA`(`area_name`)
)
ENGINE INNODB auto_increment=1 DEFAULT CHARSET=utf8;

Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第5张图片

3.HelloController

package com.cevent.springboot.wechat;/**
 * Created by Cevent on 2020/7/15.
 */

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author cevent
 * @description
 * @date 2020/7/15 20:40
 */
@RestController
public class HelloController {

    @RequestMapping(value = "/hello" , method = RequestMethod.GET)
    public String hello(){
        return "Hello Springboot Wechat";
    }
}


4.entity-area

package com.cevent.springboot.wechat.entity;/**
 * Created by Cevent on 2020/7/15.
 */

import java.util.Date;

/**
 * @author cevent
 * @description
 * @date 2020/7/15 21:04
 */
public class AreaBean {
    //1.主键ID
    private Integer areaId;
    //2.地区名称
    private String areaName;
    //3.显示的优先级
    private Integer priority;
    //4.创建时间
    private Date createTime;
    //5.最后的修改时间
    private Date lastEditTime;

    public AreaBean() {
    }

    public AreaBean(Integer areaId, String areaName, Integer priority, Date createTime, Date lastEditTime) {
        this.areaId = areaId;
        this.areaName = areaName;
        this.priority = priority;
        this.createTime = createTime;
        this.lastEditTime = lastEditTime;
    }

    public Integer getAreaId() {
        return areaId;
    }

    public void setAreaId(Integer areaId) {
        this.areaId = areaId;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public Integer getPriority() {
        return priority;
    }

    public void setPriority(Integer priority) {
        this.priority = priority;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getLastEditTime() {
        return lastEditTime;
    }

    public void setLastEditTime(Date lastEditTime) {
        this.lastEditTime = lastEditTime;
    }

    @Override
    public String toString() {
        return "AreaBean{" +
                "areaId=" + areaId +
                ", areaName='" + areaName + '\'' +
                ", priority=" + priority +
                ", createTime=" + createTime +
                ", lastEditTime=" + lastEditTime +
                '}';
    }
}


5.pom.xml配置

"1.0" encoding="UTF-8"?>
"http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0</modelVersion>
    
        org.springframework.boot</groupId>
        spring-boot-starter-parent</artifactId>
        2.3.1.RELEASE</version>
        /> <!-- lookup parent from repository -->
    </parent>
    com.cevent</groupId>
    springboot-wechat</artifactId>
    0.0.1-SNAPSHOT</version>
    springboot-wechat</name>
    Demo project for Spring Boot</description>

    
        .version>1.8</java.version>
    </properties>

    
        
            org.springframework.boot</groupId>
            spring-boot-starter-web</artifactId>
        </dependency>
        <!--MyBatis前期不需要,先注释,创建实体类entity后开启-->
        
            org.mybatis.spring.boot</groupId>
            mybatis-spring-boot-starter</artifactId>
            2.1.3</version>
        </dependency>
        <!--MySQL-->
        
            mysql</groupId>
            mysql-connector-java</artifactId>
        </dependency>
        <!--连接线程池-->
        
            com.mchange</groupId>
            c3p0</artifactId>
            0.9.5.2</version>
        </dependency>

        
            org.springframework.boot</groupId>
            spring-boot-starter-test</artifactId>
            test</scope>
            
                
                    org.junit.vintage</groupId>
                    junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    
        
            
                org.springframework.boot</groupId>
                spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


6.mybatis-config.xml

"1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

    <!--配置全局属性-->
    
        <!--1.使用jdbc的getGeneratedKeys获取数据库的自增主键值,新增一条数据时,返回实体类主键ID的自增值/自增赋值 -->
        "useGeneratedKeys" value="true"/>

        <!--2.使用useColumnLabel列标签,替换列别名,默认为true -->
        "useColumnLabel" value="true"/>
        <!--3.开启驼峰命名转换:TABLE = area_id => Entity = areaId -->
        "mapUnderscoreToCamelCase" value="true"/>
        
    </settings>


</configuration>


7.config.dao层-DataSourceConfiguration(链接数据库) JDBC-MySQL

联动 comboPooledDataSource --》 SessionFactoryConfiguration( dataSource )

package com.cevent.springboot.wechat.config.dao;/**
 * Created by Cevent on 2020/7/15.
 */

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.beans.PropertyVetoException;

/**
 * @author cevent
 * @description
 * @date 2020/7/15 21:30
 */
//@Configurattion声明spring在DataSourceConfiguration中找配置
@Configuration
//配置MyBatis mapper扫描路径
@MapperScan("com.cevent.springboot.wechat.dao")
public class DataSourceConfiguration {

    //读取properties内容
    @Value("${jdbc.driver}")
    private String jdbcDriver;
    @Value("${jdbc.url}")
    private String jdbcUrl;
    @Value("${jdbc.username}")
    private String jdbcUsername;
    @Value("${jdbc.password}")
    private String jdbcPassword;

    //注册bean
    @Bean(name = "comboPooledDataSource")
    public ComboPooledDataSource createDataSource() throws PropertyVetoException {
        //1.生成ComboPooledDataSource实例
        ComboPooledDataSource comboPooledDataSource=new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(jdbcDriver);
        comboPooledDataSource.setJdbcUrl(jdbcUrl);
        comboPooledDataSource.setUser(jdbcUsername);
        comboPooledDataSource.setPassword(jdbcPassword);
        //连接池关闭时,做自动提交,取消关闭时的自动提交=false
        comboPooledDataSource.setAutoCommitOnClose(false);

        return comboPooledDataSource;
    }
}


8.SessionFactory配置mybatis配置文件、mapper、entity,联动comboPolledDataSource

package com.cevent.springboot.wechat.config.dao;/**
 * Created by Cevent on 2020/7/15.
 */

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @author cevent
 * @description 绑定dataSource和MyBatis
 * @date 2020/7/15 21:53
 */
@Configuration
public class SessionFactoryConfiguration {

    //1.1 mybatis-config配置文件的路径
    @Value("${mybatis_config_file}")
    private String mybatisConfigFilePath;
    //1.2 mybatis-mapper文件所在路径
    @Value("${mapper_path}")
    private String mapperPath;
    //1.3 entity实体类所在的包
    @Value("${entity_package}")
    private String entityPackage;
    //1.4 引用dataSource,
    @Autowired
    @Qualifier("comboPooledDataSource")
    private DataSource dataSource;

    //1.加载Bean-SqlSessionFactoryBean
    @Bean("sqlSessionFactoryBean")
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        //2.设置myBatis-config的扫描路径
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
        //3.设置mapper文件路径:前端对数据库的请求,调用jdbc转换为MySQL能识别的sql语句,操作数据库
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver=new PathMatchingResourcePatternResolver();
        //4. 设置mapper包的查找路径 String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
        String packageMybatis=PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+mapperPath;
        //5.加载resolver
        sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageMybatis));
        //6.设置datasource
        sqlSessionFactoryBean.setDataSource(dataSource);
        //7.映射实体类-包别名:指定实体类的扫描路径
        sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);

        return sqlSessionFactoryBean;
    }
}


9.properties配置jdbc、mybatis、entity属性

server.port=8082
## Sptingboot2.1之后,需要加入servlet路径
server.servlet.context-path=/wechat

##MySQL连接池
jdbc.driver=com.mysql.jdbc.Driver
##MySQL高版本的数据库,需要指明是否为SSL的文件
jdbc.url=jdbc:mysql://127.0.0.1:3306/wechat_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=admins

###dataSourceConfig和mybatis--config、mapper配置
mybatis_config_file=mybatis-config.xml
mapper_path=/mapper/**.xml
entity_package=com.cevent.springboot.wechat.entity


10.配置dao层接口

package com.cevent.springboot.wechat.dao;

import com.cevent.springboot.wechat.entity.AreaBean;

import java.util.List;

/**
 * Created by Cevent on 2020/7/15.
 */
public interface AreaDao {

    //1.get:返回area list
    List<AreaBean> queryAreas();
    //2.get:根据id获取area
    AreaBean queryAreaById(int areaId);
    //3.POST:新建area
    int insertArea(AreaBean area);
    //4.update:更新area
    int updateArea(AreaBean area);
    //5.delete:删除area
    int deleteArea(int areaId);

}


11.自动生成junit测试方法

Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第6张图片
(2)修改找不到dao接口的wrining
配置settings  editor  code style  inspections  spring  spring core  code  autowiring for bean class
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第7张图片
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第8张图片
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第9张图片
运行测试方法报错:Mapper必须匹配configuration,mapper配置错误
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第10张图片
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第11张图片

12.配置mapper-SQL查询语句

"1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--1.mapper实现areaDao方法-->
"com.cevent.springboot.wechat.dao.AreaDao">
    <select id="queryAreas" resultType="com.cevent.springboot.wechat.entity.AreaBean">
        SELECT area_id,area_name,priority,create_time,last_edit_time
        FROM wechat_area
        ORDER BY priority
        DESC
    </select>
    <select id="queryAreaById" resultType="com.cevent.springboot.wechat.entity.AreaBean">
        SELECT area_id,area_name,priority,create_time,last_edit_time
        FROM wechat_area
        WHERE area_id=#{areaId}
    </select>
    <!--返回一个主键值,则创建成功-->
    "insertArea"
            useGeneratedKeys="true"
            keyProperty="areaId"
            keyColumn="area_id"
            parameterType="com.cevent.springboot.wechat.entity.AreaBean">
        INSERT INTO
        wechat_area
        (area_name,priority,create_time,last_edit_time)
        VALUES
        (#{areaName},#{priority},#{createTime},#{lastEditTime})
    </insert>
    <!--使用set-if进行判断测试-->
    "updateArea" parameterType="com.cevent.springboot.wechat.entity.AreaBean">
        UPDATE
        wechat_area
        <set>
            <if test="areaName!=null">area_Name=#{areaName},
            <if test="priority!=null">priority=#{priority},
            <if test="lastEditTime!=null">last_edit_time=#{lastEditTime}
        </set>
        WHERE area_id=#{areaId}
    </update>

    "deleteArea" parameterType="com.cevent.springboot.wechat.entity.AreaBean">
        DELETE FROM
        wechat_area
        WHERE
        area_id=#{areaId}
    </delete>
</mapper>


13.测试方法实现

测试方法实现
package com.cevent.springboot.wechat.dao;

import com.cevent.springboot.wechat.entity.AreaBean;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

/**
 * Created by Cevent on 2020/7/15.
 */
@SpringBootTest
class AreaDaoTest {

    //定义成员变量Dao
    @Autowired
    private AreaDao areaDao;

    @Test
    void queryAreas() {
        List<AreaBean> areas=areaDao.queryAreas();
        //assertEquals:断言是否与数据库的areas条数相等
        assertEquals(2,areas.size());
        System.out.println(areas);
    }

    @Test
    void queryAreaById() {
        AreaBean area=areaDao.queryAreaById(1);
        assertEquals("桃城区",area.getAreaName());
        System.out.println(area.getAreaName());
    }

    @Test
    void insertArea() {
        AreaBean area=new AreaBean();
        area.setAreaName("武强县");
        area.setPriority(1);
        int effectedNum=areaDao.insertArea(area);
        assertEquals(1,effectedNum);
        System.out.println("武强县创建成功,effectedNum= "+effectedNum);
    }

    @Test
    void updateArea() {
        AreaBean area=new AreaBean();
        area.setAreaId(3);
        area.setAreaName("乌兰察布市");
        area.setLastEditTime(new Date());
        int effectedNum=areaDao.updateArea(area);
        assertEquals(1,effectedNum);
        System.out.println("武强县更新成功-->乌兰察布市,effectedNum= "+effectedNum);
    }

    @Test
    void deleteArea() {
        int effectedNum=areaDao.deleteArea(3);
        assertEquals(1,effectedNum);
        System.out.println("乌兰察布市删除成功---> "+effectedNum);
    }
}


13.1查询遍历areas

//定义成员变量Dao
@Autowired
private AreaDao areaDao;

@Test
void queryAreas() {
    List<AreaBean> areas=areaDao.queryAreas();
    //assertEquals:断言是否与数据库的areas条数相等
    assertEquals(2,areas.size());
    System.out.println(areas);
}


Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第12张图片

13.2根据id获取area

@Test
void queryAreaById() {
    AreaBean area=areaDao.queryAreaById(1);
    assertEquals("桃城区",area.getAreaName());
    System.out.println(area.getAreaName());
}


Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第13张图片

13.3新建area

@Test
void insertArea() {
    AreaBean area=new AreaBean();
    area.setAreaName("武强县");
    area.setPriority(1);
    int effectedNum=areaDao.insertArea(area);
    assertEquals(1,effectedNum);
    System.out.println("武强县创建成功,effectedNum= "+effectedNum);
}


Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第14张图片
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第15张图片

13.4根据id更新area

@Test
void updateArea() {
    AreaBean area=new AreaBean();
    area.setAreaId(3);
    area.setAreaName("乌兰察布市");
    area.setLastEditTime(new Date());
    int effectedNum=areaDao.updateArea(area);
    assertEquals(1,effectedNum);
    System.out.println("武强县更新成功-->乌兰察布市,effectedNum= "+effectedNum);
}


4
4

13.5根据id删除area

根据id删除area
@Test
void deleteArea() {
    int effectedNum=areaDao.deleteArea(3);
    assertEquals(1,effectedNum);
    System.out.println("乌兰察布市删除成功---> "+effectedNum);
}


5
5

14.Service层实现,配置spring及接口

14.1事务配置TransactionManagementConfiguration

package com.cevent.springboot.wechat.config.service;/**
 * Created by Cevent on 2020/7/16.
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.sql.DataSource;

/**
 * @author cevent
 * @description 配置service层事务管理:需要实现TransactionManagementConfiguration
 * @date 2020/7/16 13:27
 */
@Configuration
@EnableTransactionManagement
public class TransactionManagementConfiguration implements TransactionManagementConfigurer {

    //实现dataSource接口
    @Autowired
    @Qualifier("comboPooledDataSource")
    private DataSource dataSource;

    @Override
    public TransactionManager annotationDrivenTransactionManager() {
        //返回dataSource事务
        return new DataSourceTransactionManager(dataSource);
    }
}


14.2service接口层

package com.cevent.springboot.wechat.service;/**
 * Created by Cevent on 2020/7/16.
 */

import com.cevent.springboot.wechat.entity.AreaBean;

import java.util.List;

/**
 * @author cevent
 * @description Service层不一定和dao层的方法一样(不一一对应),可能囊括多个dao层的方法
 * @date 2020/7/16 13:35
 */
public interface AreaService {
    //1.get:返回area list
    List<AreaBean> queryAreas();
    //2.get:根据id获取area
    AreaBean queryAreaById(int areaId);

    /*int返回值转为boolean*/
    //3.POST:新建area
    boolean insertArea(AreaBean area);
    //4.update:更新area
    boolean updateArea(AreaBean area);
    //5.delete:删除area
    boolean deleteArea(int areaId);
}


14.3serviceImple实现

package com.cevent.springboot.wechat.service.impl;/**
 * Created by Cevent on 2020/7/16.
 */

import com.cevent.springboot.wechat.dao.AreaDao;
import com.cevent.springboot.wechat.entity.AreaBean;
import com.cevent.springboot.wechat.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author cevent
 * @description Server层方法实现
 * @date 2020/7/16 13:37
 */
@Service
public class AreaServiceImpl implements AreaService {

    @Autowired
    private AreaDao areaDao;

    @Override
    public List<AreaBean> queryAreas() {
        return areaDao.queryAreas();
    }

    @Override
    public AreaBean queryAreaById(int areaId) {
        return areaDao.queryAreaById(areaId);
    }

    //涉及到增删的操作,需要加入事务@Transactional回滚事务,默认接收RuntimeException
    /* @Transactional(rollbackFor = Exception.class)
       也可以自定义异常名rollbackFor = Exception.class
     */
    @Transactional
    @Override
    public boolean insertArea(AreaBean area) {
        //不为空判定
        if(area.getAreaName()!=null && !"".equals(area.getAreaName())){
            area.setCreateTime(new Date());
            area.setLastEditTime(new Date());
            try {
                int effectedNum=areaDao.insertArea(area);
                if(effectedNum>0){
                    System.out.println("新建地区成功!");
                    return true;
                }else{
                    throw new RuntimeException("新建地区失败failed!");
                }
            }catch (Exception e){
                throw new RuntimeException("新建地区失败failed: "+e.getMessage());
            }
        }else{
            throw new RuntimeException("区域信息不能为空~~~!");
        }
    }

    @Transactional
    @Override
    public boolean updateArea(AreaBean area) {
        //areaId不为空判断
        if(area.getAreaId()!=null && area.getAreaId()>0){
            //设置默认时间
            area.setLastEditTime(new Date());
            try {
                //更新地区信息
                int effectNum=areaDao.updateArea(area);
                if(effectNum>0){
                    System.out.println("修改地区成功!");
                    return true;
                }else{
                    throw new RuntimeException("修改地区失败failed:!");
                }
            }catch (Exception e){
                throw new RuntimeException("修改地区失败failed: "+e.getMessage());
            }
        }else{
            throw new RuntimeException("区域ID不能为空~~~!");
        }
    }

    @Transactional
    @Override
    public boolean deleteArea(int areaId) {
        //areaId大于0
        if(areaId>0){
            try {
                int effectedNum=areaDao.deleteArea(areaId);
                if(effectedNum>0){
                    System.out.println("删除地区成功:地区id--> "+areaId);
                    return true;
                }else {
                    throw new RuntimeException("删除地区失败failed: ");
                }
            }catch (Exception e){
                throw new RuntimeException("删除地区失败failed: "+e.getMessage());
            }

        }else{
            throw new RuntimeException("区域ID不能为空~~~!");
        }
    }
}


14.4Controller层

package com.cevent.springboot.wechat.web;/**
 * Created by Cevent on 2020/7/16.
 */

import com.cevent.springboot.wechat.entity.AreaBean;
import com.cevent.springboot.wechat.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cevent
 * @description 控制层-->service implements
 * @RestController= @Controller + ResponseBody
 * @RequestMapping("/指定项目根路径/根路由")
 * @date 2020/7/16 14:13
 */
@RestController
@RequestMapping("/supercevent")
public class AreaController {
    @Autowired
    private AreaService areaService;

    //1.返回区域的所有信息
    @RequestMapping(value="/areas",method = RequestMethod.GET)
    private Map<String , Object> areas(){
        Map<String,Object> modelMap=new HashMap<String,Object>();
        List<AreaBean> areas=areaService.queryAreas();
        modelMap.put("areaList",areas);
        return modelMap;
    }

    //2.根据id获取area
    @RequestMapping(value = "/getareabyid",method = RequestMethod.GET)
    private Map<String,Object> getAreaById(Integer areaId){
        Map<String,Object> modelMap=new HashMap<String,Object>();
        AreaBean area=areaService.queryAreaById(areaId);
        modelMap.put("area",area);
        return modelMap;
    }

    //3.新增area,前端传送的数据:json、xml(@RequestBody)、x3w url encoded
    @RequestMapping(value = "/addarea",method = RequestMethod.POST)
    private Map<String,Object> addArea(@RequestBody AreaBean area){
        Map<String,Object> modelMap=new HashMap<String,Object>();
        //这里返回的是boolean
        modelMap.put("success",areaService.insertArea(area));
        return modelMap;
    }

    //4.更新area
    @RequestMapping(value = "/updatearea",method = RequestMethod.POST)
    private Map<String,Object> updateArea(@RequestBody AreaBean area){

        Map<String,Object> modelMap=new HashMap<String,Object>();
        modelMap.put("success",areaService.updateArea(area));
        return modelMap;
    }

    //5.删除area
    @RequestMapping(value = "/removearea",method = RequestMethod.GET)
    private Map<String,Object> removeArea(Integer areaId){
        Map<String,Object> modelMap=new HashMap<String, Object>();
        modelMap.put("success",areaService.deleteArea(areaId));
        return modelMap;
    }

}


获取area列表:http://localhost:8082/wechat/supercevent/areas
14
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第16张图片

15.Springboot(Controller、service、dao)统一异常处理

package com.cevent.springboot.wechat.handler;/**
 * Created by Cevent on 2020/7/16.
 */

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cevent
 * @description 统一异常处理类
 * @date 2020/7/16 14:43
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    private Map<String,Object> exceptionHandler(HttpServletRequest request,Exception e){
      Map<String,Object> modelMap=new HashMap<String,Object>();
      modelMap.put("success",false);
      modelMap.put("errorMsg",e.getMessage());
      //返回异常数据
      return modelMap;
    }

}


16.测试getAreaById异常

@Service
public class AreaServiceImpl implements AreaService {

    @Autowired
    private AreaDao areaDao;

    @Override
    public List<AreaBean> queryAreas() {
        return areaDao.queryAreas();
    }

    @Override
    public AreaBean queryAreaById(int areaId) {
        //测试全局异常GlobalExceptionHandler
        int a=1/0;
        return areaDao.queryAreaById(areaId);
    }


访问:http://localhost:8082/wechat/supercevent/getareabyid?areaId=1
16
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第17张图片

17.小程序创建配置说明

Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第18张图片
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第19张图片
17
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第20张图片

18.area列表展示

Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第21张图片

18.1通过index.js设置跳转

Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第22张图片
跳转页面显示

{
  "navigationBarTileText": "区域信息列表"
}


Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第23张图片
Wxml页面属性

<!--text作用,生成页面文本-->
<text>pages/list/list.wxml</text>



18.2视图容器view

https://developers.weixin.qq.com/miniprogram/dev/component/view.html
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第24张图片
调试器全开检查bug
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第25张图片
开启不校验安全域名及https
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第26张图片

18.3点击头像激活onShow函数调用get请求,实现遍历区域

index.js

//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../list/list'
    })
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})



18.4 list.wxml

<!--1.添加整个页面的视图容器view-->
<view class="container">
  <view class="viewWidth">
    <text class="column">ID</text>
    <text class="column">区域</text>
    <text class="column">优先级</text>
    <text class="link-column">操作</text>
  </view>

  <scroll-view scroll-y="true">
    <view>
      <!--添加block数据块
    wx:for更新性能优化报错: Now you can provide attr `wx:key` for a `wx:for`
    wx:key="key" wx:for-item="item"
    -->
      <block wx:for="{{list}}" wx:key="key" wx:for-item="item">
        <view class="viewWidth">
          <text class="column">{{item.areaId}}</text>
          <text class="column">{{item.areaName}}</text>
          <text class="column">{{item.priority}}</text>
          <view class="link-column">
            <!--navigator重定向 bindtap=click点击事件-->
            <navigator class="link-edit" url="../operation/operation?areaId={{item.areaId}}">编辑</navigator>
          <text class="line">||</text>

            <!--data-index将页面内的area删除-->
            <text class="link-delete" bindtap="deleteArea" data-areaid="{{item.areaId}}"
              data-areaname="{{item.areaName}}" data-index="{{index}}">删除</text>
          </view>
        </view>
      </block>

    </view>
  </scroll-view>

  <button type="primary" bindtap="addArea">添加区域信息</button>
</view>


18.5list.wxss

/* pages/list/list.wxss */
.viewWidth {
  position: relative;
  margin-top: 5rpx;
  margin-bottom: 5rpx; 
  padding-top: 10rpx;
  padding-bottom: 10rpx; 
  padding-left: 40rpx;
  padding-right: 40rpx; 
  border: #ddd 1px solid; 
  }
  
.container {
  height: 100%;
  display: table;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding-top: 10rpx;
  padding-bottom: 10rpx;
  text-align: center;
  }
  
  .column {
  width: 4rem;
  display: table-cell;
  }
  
  .link-column {
  width: 6rem;
  display: table-cell;
  }
  
  .link {
  color: blue;
  display: inline-table;
  }
  
  .link-edit{
  color:green;
  display: inline-table;  
  }

  .link-delete{
  color:orange;
  display: inline-table;  
  }
.line {
  color: skyblue;
  display: inline-table;
  margin: 5px;
}



18.6list.js

// pages/list/list.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   * 需要添加返回页面时的重新加载
   */
  onShow: function () {

    //that: 保存当前焦点/句柄
    var that=this;
    wx.request({
      url: "http://192.168.70.1:8082/wechat/supercevent/areas",
      method: 'GET',
      data: {},
      success: function(result){
        //这里data的返回值必须与controller的返回值modelMap中设置的key一致
        var areas=result.data.areaList;
        if(areas==null){
          var toastText="获取信息失败"+result.data.errorMsg;
          wx.showToast({
            title: toastText,
            icon: '',
            duration: 2000
          });
        }else{
          that.setData({
            list:areas
          });
        }
      }
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})


Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第27张图片

19删除

19.1list.wxml

<!--1.添加整个页面的视图容器view-->
<view class="container">
  <view class="viewWidth">
    <text class="column">ID</text>
    <text class="column">区域</text>
    <text class="column">优先级</text>
    <text class="link-column">操作</text>
  </view>

  <scroll-view scroll-y="true">
    <view>
      <!--添加block数据块
    wx:for更新性能优化报错: Now you can provide attr `wx:key` for a `wx:for`
    wx:key="key" wx:for-item="item"
    -->
      <block wx:for="{{list}}" wx:key="key" wx:for-item="item">
        <view class="viewWidth">
          <text class="column">{{item.areaId}}</text>
          <text class="column">{{item.areaName}}</text>
          <text class="column">{{item.priority}}</text>
          <view class="link-column">
            <!--navigator重定向 bindtap=click点击事件-->
            <navigator class="link-edit" url="../operation/operation?areaId={{item.areaId}}">编辑</navigator>
            <text class="line">||</text>
            <!--data-index将页面内的area删除-->
            <text class="link-delete" bindtap="deleteArea" data-areaid="{{item.areaId}}"
              data-areaname="{{item.areaName}}" data-index="{{index}}">删除</text>
          </view>
        </view>
      </block>

    </view>
  </scroll-view>

  <button type="primary" bindtap="addArea">添加区域信息</button>
</view>


19.2list.js

list.js
//删除区域: dataset.areaname=data-areaname/id
    deleteArea: function(val){
      var that=this;
      wx.showModal({
        title: '提示',
        content: '确定要删除 [ '+val.target.dataset.areaname+' ] 吗?',
        success: function(showModel){
          if(showModel.confirm){
            wx.request({
              url: 'http://192.168.70.1:8082/wechat/supercevent/removearea',
              data:{"areaId":val.target.dataset.areaid},
              method:'GET',
              success: function(result){
                var result=result.data.success;
                var toastText="删除成功!";
                if(result!=true){
                  toastText="删除失败";
                }else{
                  //指定删除页面的数据,1=指定删除1行
                  that.data.list.splice(val.target.dataset.index,1);
                  that.setData({
                    list: that.data.list
                  });
                }
                //发出succ/fail的信息轻提示
                wx.showToast({
                  title: toastText,
                  icon: '',
                  duration: 2000
                });
              }
            });
          }
        }
  
      });
    },


19.3实现

Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第28张图片

20信息编辑页面

20.1operation.wxml

<!--pages/operation/opetation.wxml-->
<view class="container">
  <form bindsubmit="formSubmit" bindreset="formReset">
    <view class="row">
      <text>区域名:</text>
      <input type="text" name="areaName" placeholder="请输入区域名" value="{{areaName}}"/>
    </view>
    <view class="row">
      <text>优先级:</text>
      <input type="text" name="priority" placeholder="优先级越大排序靠前" value="{{priority}}"/>
    </view>
    <view class="row">
      <button type="primary" form-type="submit">提交</button>
      <button type="primary" form-type="reset">重置</button>
    </view>
  </form>
</view>



20.2operation.json

{
  "navigationBarTitleText": "区域信息表单"
}


20.3operation.js

// pages/operation/opetation.js
Page({

  /**
   * 页面的初始数据
   * areaId: undefined定义未定义,判断跳转时是否携带了areaId,确定是添加/更新页面
   */
  data: {
    areaId: undefined,
    areaName: '',
    priority: '',
    addUrl: 'http://192.168.70.1:8082/wechat/supercevent/addarea',
    updateUrl: 'http://192.168.70.1:8082/wechat/supercevent/updatearea'
  },

  /**
   * 生命周期函数--监听页面加载
   * 每次打开页面都需要重新加载,可以使用onLoad一次性获取页面参数
   */
  onLoad: function (options) {
    var that=this;
    // 页面初始化,页面跳转携带的参数-->options
    this.setData({
      areaId:options.areaId
    });
    if(options.areaId==undefined){
      //如果没有,直接返回空
      return;
    }
    wx.request({
      url: 'http://192.168.70.1:8082/wechat/supercevent/getareabyid',
      data: {"areaId":options.areaId},
      method: 'GET',
      success: function success(result){
        //data的area与modelMap的key一直-->注意
        var area=result.data.area;
        if(area==undefined){
          var toastText='获取数据失败'+result.data.errorMsg;
          wx.showToast({
            title: toastText,
            icon: '',
            duration: 2000
          });
        }else{
          that.setData({
            areaName: area.areaName,
            priority: area.priority
          });
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  //提交表单
  formSubmit:function(val){
    var that=this;
    //将detail的内存value存入formData
    var formData=val.detail.value;
    var url=that.data.addUrl;
    //判断add/edit url不为空则=更新数据表单
    if(that.data.areaId!=undefined){
      //更新表单需要传递areaId
      formData.areaId=that.data.areaId;
      url=that.data.updateUrl
    }
    //data需要json转换
    wx.request({
      url: url,
      data: JSON.stringify(formData),
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      //这里的result对应service的返回值类型boolean
      success:function(result){
        var result=result.data.success;
        var toastText="提交区域成功";
        if(result!=true){
          toastText="提交失败"+result.data.errorMsg;
        }
        wx.showToast({
          title: toastText,
          icon: '',
          duration: 2000
        });
        //添加数据成功,跳转到list
        if(that.data.areaId==undefined){
          wx.redirectTo({
            url: '../list/list',
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})


20.4wxss

/* pages/operation/opetation.wxss */
.container{

  padding: 1rem;
  
  font-size: 0.9rem;
  
  line-height: 1.56rem;
  
  }
  
  .row{
  
  display: flex;
  
  align-items: center;
  
  margin-bottom: 0.8rem;
  
  }
  
  .row text{
  
  flex-grow: 1;
  
  text-align: right;
  
  }
  
  .row input{
  
  font-size: 0.7rem;
  
  flex-grow: 3;
  
  border: 1px solid #0099CC;
  
  display: inline-block;
  
  border-radius: 0.3rem;
  
  box-shadow: 0 0 0.15rem #aaa;
  
  padding: 0.3rem;
  
  }
  
  .row button{
  
  padding: 0 2rem;
  
  margin: 3rem 1rem;
  
  }
  
  


20.5实现

Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第29张图片
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第30张图片
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第31张图片
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第32张图片
Springboot单应用+mybatis-微信小程序配置详细介绍:实现服务层增删改查应用Springboot(Controller、service、dao)统一异常处理_第33张图片

你可能感兴趣的:(springboot,mybatis,微信小程序)