SpringBoot2(三):整合mybatis完整版

2018-12-29  本文已影响0人  帅气滴糟老头

1. 修改pom.xml文件

添加mybatis、mysql、逆向工程,连接池等依赖

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.10</version>
        </dependency>
        <!-- mybatis-generator-core 反向生成java代码-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>
        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

配置mybatis逆向工程maven插件

        <!--mybatis逆向工程maven插件-->
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.5</version>
            <configuration>
                <!--允许移动生成的文件-->
                <verbose>true</verbose>
                <!--允许覆盖生成的文件-->
                <overwrite>true</overwrite>
                <!--配置文件的路径 默认resources目录下-->
                <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
            </configuration>
            <!--插件依赖的jar包-->
            <dependencies>
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>8.0.13</version>
                </dependency>
            </dependencies>
        </plugin>

2. 配置application.yml

server:
  port: 8080

spring:
  datasource:
    name: mysql_test
    #基本属性
    url: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE&serverTimezone=UTC&allowMultiQueries=true
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource
    #druid相关配置
    druid:
      #监控统计拦截的filters
      filters: stat
      #配置初始化大小/最小/最大
      initial-size: 1
      min-idle: 1
      max-active: 20
      #获取连接等待超时时间
      max-wait: 60000
      #间隔多久进行一次检测,检测需要关闭的空闲连接
      time-between-eviction-runs-millis: 60000
      #一个连接在池中最小生存的时间
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 'x'
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
      pool-prepared-statements: false
      max-pool-prepared-statement-per-connection-size: 20

mybatis:
  #映射文件所在路径
  mapper-locations: classpath:com.along.mapper/*.xml
  #pojo类所在包路径
  type-aliases-package: com.along.entity
  configuration:
    #配置项:开启下划线到驼峰的自动转换. 作用:将数据库字段根据驼峰规则自动注入到对象属性。
    map-underscore-to-camel-case: true

#pagehelper
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql

logging:
  level:
    #打印SQL信息
    com.along.dao: debug

3. 在resource下添加逆向工程配置文件generatorConfig.xml,内容如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!--
        targetRuntime="MyBatis3", 生成 Example相关类及方法
        targetRuntime="MyBatis3Simple",不生成 Example相关类及方法
    -->
    <context id="MysqlTables" targetRuntime="MyBatis3">
        <!-- 指定生成 Mapper 的继承模板 -->
        <!--<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="" />
        </plugin>-->
        <!-- 生成 JavaBean 对象重写 toString方法 -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
        <!-- 生成 JavaBean 对象继承 Serializable 类 -->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
        <!-- 生成 JavaBean 对象重写 equals 和 hashCode 方法 -->
        <!--<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" />-->

        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1/test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8&amp;autoReconnect=true&amp;rewriteBatchedStatements=TRUE&amp;serverTimezone=UTC"
                        userId="root"
                        password="root">
        </jdbcConnection>
        <javaTypeResolver>
            <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
                NUMERIC 类型解析为java.math.BigDecimal -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.along.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="com.along.dao" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--
            生成DAO的包名和位置
            type="ANNOTATEDMAPPER", 生成Java Model 和基于注解的Mapper对象
            type="MIXEDMAPPER", 生成基于注解的Java Model 和相应的Mapper对象
            type="XMLMAPPER", 生成SQLMap XML文件和独立的Mapper接口
        -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.along.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
        <table tableName="person" domainObjectName="Person">
            <!--<generatedKey column="id" sqlStatement="JDBC" identity="true"/>-->
            <!-- Mysql 配置 -->
            <generatedKey column="id" sqlStatement="Mysql" identity="true" />
            <!-- Oracle 配置 -->
            <!-- <generatedKey column="id" sqlStatement="select SEQ_{1}.nextval from dual" identity="false" type="pre"/> -->
        </table>
        <!--<table tableName="person" domainObjectName="Person"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>-->
    </context>
</generatorConfiguration>

注意:springboot2的mysql驱动是com.mysql.cj.jdbc.Driver

4. 利用idea启动逆向工程生成代码

在pom.xml文件上右键,操作如下图

下图中红框部分为自动生成的代码

5. 修改启动类

@EnableTransactionManagement开启注解
@MapperScan({"com.along.dao"})扫描包路径,不加这个的话需要在每个mapper文件上添加@Mapper注解

@SpringBootApplication
@EnableTransactionManagement // 开启事务管理
@MapperScan({"com.along.dao"}) // 扫描包路径
public class SpringBootMybatis2Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootMybatis2Application.class, args);
    }
}

6. 实现批量删除和批量更新

逆向工程生成的代码只实现了最基本的crud,要想批量删除和更新需要自己手动实现
在PersonMapper.java中新增批量删除和更新的接口

    /**
     * 批量插入
     * @param list
     * @return
     */
    int insertBatchSelective(List list);

    /**
     * 批量更新
     * @param list
     * @return
     */
    int updateBatchByPrimaryKeySelective(List list);

然后在PersonMapper.xml中编写相应的sql语句
下面是批量插入代码:

    <!--批量插入-->
    <insert id="insertBatchSelective" parameterType="java.util.List">
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into person
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="list[0].name != null">
                name,
            </if>
            <if test="list[0].age != null">
                age,
            </if>
            <if test="list[0].address != null">
                address,
            </if>
        </trim>
        values
        <foreach collection="list" index="index" item="item" separator=",">
            <trim prefix=" (" suffix=")" suffixOverrides=",">
                <if test="item.name != null">
                    #{item.name,jdbcType=VARCHAR},
                </if>
                <if test="item.age != null">
                    #{item.age,jdbcType=INTEGER},
                </if>
                <if test="item.address != null">
                    #{item.address,jdbcType=VARCHAR},
                </if>
            </trim>
        </foreach>
    </insert>

下面是批量更新代码:

<!--批量更新
    注意:这种方法要想成功,需要在db链接url后面带一个参数 &allowMultiQueries=true-->
<update id="updateBatchByPrimaryKeySelective" parameterType="java.util.List">
    <foreach collection="list" index="index" item="item" separator=";">
        update person
        <set>
            <if test="item.name != null">
                name = #{item.name,jdbcType=VARCHAR},
            </if>
            <if test="item.age != null">
                age = #{item.age,jdbcType=INTEGER},
            </if>
            <if test="item.address != null">
                address = #{item.address,jdbcType=VARCHAR},
            </if>
        </set>
        where id = #{item.id,jdbcType=BIGINT}
    </foreach>
</update>

特别注意:要想用上面的方法实现批量更新,需要在db链接url后面带一个参数 &allowMultiQueries=true,否则会更新失败

7.测试

service层接口:PersonService.java

/**
 * @Description: service接口
 * @Author along
 * @Date 2018/12/28 17:42
 */
public interface PersonService {

    /**
     * 添加
     * @param person
     * @return
     */
    Integer add(Person person);

    /**
     * 查询全部
     * @param pageNum
     * @param pageSize
     * @return
     */
    PageInfo<Person> findAllPerson(int pageNum, int pageSize);

    /**
     * 根据名字查询
     * @param name
     * @return
     */
    PageInfo<Person> findByName(String name);

    /**
     * 批量插入
     * @param list
     * @return
     */
    int insertBatch(List<Person> list);

    /**
     * 批量更新
     * @param list
     * @return
     */
    int updateBatch(List<Person> list);
}

service层实现类:PersonServiceImpl.java

/**
 * @Description: service实现
 * @Author along
 * @Date 2018/12/28 17:44
 */
@Service(value = "personService")
@Transactional
public class PersonServiceImpl implements PersonService {

    @SuppressWarnings("all")
    @Autowired
    private PersonMapper personMapper;

    @Override
    public Integer add(Person person) {
        return personMapper.insert(person);
    }

    @Override
    public PageInfo<Person> findAllPerson(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PersonExample example = new PersonExample();
        List<Person> personList = personMapper.selectByExample(example);
        return new PageInfo<>(personList);
    }

    @Override
    public PageInfo<Person> findByName(String name) {
        PersonExample example = new PersonExample();
        PersonExample.Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(name);
        List<Person> personList = personMapper.selectByExample(example);
        return new PageInfo<>(personList);
    }

    @Override
    public int insertBatch(List<Person> list) {
        return personMapper.insertBatchSelective(list);
    }

    @Override
    public int updateBatch(List<Person> list) {
        return personMapper.updateBatchByPrimaryKeySelective(list);
    }
}

上面的查询实现用了分页查询,分页查询使用非常简单,一看便知。
下面是controller层:PersonController.java

/**
 * @Description: controller
 * @Author along
 * @Date 2018/12/28 18:02
 */
@RestController
@RequestMapping("person")
public class PersonController {

    @Autowired
    private PersonService personService;

    @PostMapping("add")
    public int addPerson(@RequestBody Person person) {
        return personService.add(person);
    }

    @GetMapping("all")
    public PageInfo findAllPerson(
            @RequestParam(name = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize) {

        return personService.findAllPerson(pageNum,pageSize);
    }

    @GetMapping("get/{name}")
    public PageInfo findByName(@PathVariable String name) {
        return personService.findByName(name);
    }

    @PostMapping("insert/batch")
    public Integer insertBatch(@RequestBody List<Person> personList) {
        return personService.insertBatch(personList);
    }

    @PostMapping("update/batch")
    public Integer updateBatch(@RequestBody List<Person> personList) {
        return personService.updateBatch(personList);
    }
}

启动项目测试,测试结果省略。

源码地址

本文地址:
https://github.com/alonglong/spring-boot-all/tree/master/spring-boot-mybatis2
另外附上注解版地址:
https://github.com/alonglong/spring-boot-all/tree/master/spring-boot-mybatis

上一篇 下一篇

猜你喜欢

热点阅读