专栏名称: hryou0922
目录
相关文章推荐
51好读  ›  专栏  ›  hryou0922

Spring Boot系列六 Spring boot集成mybatis、分页插件pagehelper

hryou0922  · 掘金  ·  · 2018-01-27 13:20

正文

1. 概述

本文的内容包括如下内容:

  1. Spring Boot集成mybatis
  2. Spring Boot集成pagehelper分页插件,定义分页的相关类
  3. 实现工具类:model转dto,实现数据层和传输层的解耦
  4. 完整展示了从浏览器输入URL,并从数据库操作数据的完整流程

2. Spring Boot集成Mybatis

2.1. pom.xml

mybatis和数据库的相关的jar

<!-- druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.31</version>
</dependency>
<!-- Spring Boot集成mybatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
</dependency>

2.2. Mapper java类和xml及Model

测试表sql如下

CREATE TABLE `test`.`test` (
  `id` INT NOT NULL,
  `age` INT NULL,
  `name` VARCHAR(45) NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `id_UNIQUE` (`id` ASC));

表对应Model类: com.hry.spring.mybatis.model.TestModel

public class TestModel {
    private Integer id;

    private Integer age;

    private String name;
   // set/get略
}

配置Mapper类: com.hry.spring.mybatis.mapper.TestMapper

public interface TestMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(TestModel record);

    int insertSelective(TestModel record);

    TestModel selectByPrimaryKey(Integer id);

    List<TestModel> selectAll();

    int updateByPrimaryKeySelective(TestModel record);

    int updateByPrimaryKey(TestModel record);
}

配置Mapper xml: TestMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hry.spring.mybatis.mapper.TestMapper">
 <resultMap id="BaseResultMap" type="com.hry.spring.mybatis.model.TestModel">
   <id column="id" jdbcType="INTEGER" property="id" />
   <result column="age" jdbcType="INTEGER" property="age" />
   <result column="name" jdbcType="VARCHAR" property="name" />
 </resultMap>
 <sql id="Base_Column_List">
   id, age, name
 </sql>
 <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
   select 
   <include refid="Base_Column_List" />
   from test
   where id = #{id,jdbcType=INTEGER}
 </select>
 <select id="selectAll"  resultMap="BaseResultMap">
   select
   <include refid="Base_Column_List" />
   from test
     order by id desc
 </select>

 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
   delete from test
   where id = #{id,jdbcType=INTEGER}
 </delete>
 <insert id="insert" parameterType="com.hry.spring.mybatis.model.TestModel">
   insert into test (id, age, name, 
     )
   values (#{id,jdbcType=INTEGER}, #{age,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}
    )
 </insert>
 <insert id="insertSelective" parameterType="com.hry.spring.mybatis.model.TestModel">
   insert into test
   <trim prefix="(" suffix=")" suffixOverrides=",">
     <if test="id != null">
       id,
     </if>
     <if test="age != null">
       age,
     </if>
     <if test="name != null">
       name,
     </if>

   </trim>
   <trim prefix="values (" suffix=")" suffixOverrides=",">
     <if test="id != null">
       #{id,jdbcType=INTEGER},
     </if>
     <if test="age != null">
       #{age,jdbcType=INTEGER},
     </if>
     <if test="name != null">
       #{name,jdbcType=VARCHAR},
     </if>

   </trim>
 </insert>
 <update id="updateByPrimaryKeySelective" parameterType="com.hry.spring.mybatis.model.TestModel">
   update test
   <set>
     <if test="age != null">
       age = #{age,jdbcType=INTEGER},
     </if>
     <if test="name != null">
       name = #{name,jdbcType=VARCHAR},
     </if>
   </set>
   where id = #{id,jdbcType=INTEGER}
 </update>
 <update id="updateByPrimaryKey" parameterType="com.hry.spring.mybatis.model.TestModel">
   update test
   set age = #{age,jdbcType=INTEGER},
     name = #{name,jdbcType=VARCHAR}
   where id = #{id,jdbcType=INTEGER}
 </update>
</mapper>

2.3. mybatis配置

spring_mybatis.xml
spring.datasource.url的值配置在application.yml

<!-- ### 配置数据源 begin ###-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 
  <!-- 基本属性 url、user、password -->
  <property name="url" value="${spring.datasource.url}" />
  <property name="username" value="${spring.datasource.username}" />
  <property name="password" value="${spring.datasource.password}" />
  <property name="driverClassName" value="${spring.datasource.driverClassName}" />


  <!-- 配置初始化大小、最小、最大 -->
  <property name="initialSize" value="${spring.datasource.initialSize:5}" />
  <property name="minIdle" value="${spring.datasource.minIdle:5}" /> 
  <property name="maxActive" value="${spring.datasource.maxActive:20}" />

  <!-- 配置获取连接等待超时的时间 -->
  <property name="maxWait" value="${spring.datasource.maxWait:30000}" />

  <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
  <property name="timeBetweenEvictionRunsMillis" value="${spring.datasource.timeBetweenEvictionRunsMillis}" />

  <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
  <property name="minEvictableIdleTimeMillis" value="${spring.datasource.minEvictableIdleTimeMillis}" />

  <property name="validationQuery" value="${spring.datasource.validationQuery}" />
  <property name="testWhileIdle" value="${spring.datasource.testWhileIdle}" />
  <property name="testOnBorrow" value="${spring.datasource.testOnBorrow}" />
  <property name="testOnReturn" value="${spring.datasource.testOnReturn}" />

  <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
  <property name="poolPreparedStatements" value="${spring.datasource.poolPreparedStatements}" />
  <property name="maxPoolPreparedStatementPerConnectionSize" value="${spring.datasource.maxPoolPreparedStatementPerConnectionSize}" />

  <!-- 配置监控统计拦截的filters -->
  <property name="filters" value="${spring.datasource.filters}" />

  <property name="connectionProperties" value="{spring.datasource.connectionProperties}" />
</bean>
<!-- ### 配置数据源  end ###-->

<!-- ### Mybatis和事务配置  begin ###-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!-- 配置扫描Mapper XML的位置 -->
    <property name="mapperLocations" value="classpath:com/hry/spring/mybatis/mapper/*.xml"/>
    <!-- 配置mybatis配置文件的位置 -->
    <property name="configLocation" value="classpath:config/spring/mybatis_config.xml"/>

</bean>

<!-- 配置扫描Mapper接口的包路径 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.hry.spring.mybatis.mapper"/>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>

<!-- 事务配置 -->
<bean id="transactionManager"
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
      p:dataSource-ref="dataSource"/>

<tx:advice id="txAdvice" transaction-manager="transactionManager" >
    <tx:attributes>
        <tx:method name="add*" propagation="REQUIRED" />
    <tx:method name="create*" propagation="REQUIRED" />
    <tx:method name="save*" propagation="REQUIRED" />
        <tx:method name="insert*" propagation="REQUIRED" />
    <tx:method name="update*" propagation="REQUIRED" />
    <tx:method name="batch*" propagation="REQUIRED" />
    <tx:method name="del*" propagation="REQUIRED" />
    <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
    <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
        <tx:method name="*" read-only="true"/>
    </tx:attributes>
</tx:advice>
<aop:config >
    <aop:pointcut id="pt" expression="execution(* com.hry.spring.mybatis.service..*.*(..))" />
    <aop:advisor pointcut-ref="pt" advice-ref="txAdvice"/>
</aop:config> 
<!-- ### Mybatis和事物配置  end ###-->

mybatis_config.xml

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

</configuration>

2.4. application.yml

配置数据库的信息如下:

# 数据库配置
spring:
  datasource:
    #### Datasource 配置 ####
    type: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: root
    url: jdbc:mysql://127.0.0.1:3306/test?zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2b8&useSSL=true
    # url: jdbc:mysql://127.0.0.1:3306/test
    driverClassName: com.mysql.cj.jdbc.Driver
    # driverClassName: oracle.jdbc.driver.OracleDriver
    # 下面为连接池的补充设置,应用到上面所有数据源中# 初始化大小,最小,最大
    initialSize: 5
    minIdle: 5
    maxActive: 20
    # 配置获取连接等待超时的时间
    maxWait: 30000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    minEvictableIdleTimeMillis: 300000
    timeBetweenEvictionRunsMillis: 60000
    validationQuery: SELECT 1 FROM DUAL
    # 打开PSCache,并且指定每个连接上PSCache的大小
    poolPreparedStatements: false
    maxPoolPreparedStatementPerConnectionSize: 20
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: log4j
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

2.5. spring boot集成mybatis

通过@ImportResource加载mybatis的配置 用@Bean注解的方法fastJsonHttpMessageConverters表示使用fastjson解析json

@SpringBootApplication
// 加载mybatis配置
@ImportResource({"classpath:config/spring/spring_*.xml"})
public class MybatisSpringBoot {
    public static void main(String[] args){
        SpringApplication.run(MybatisSpringBoot.class, args);
    }

    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        // 格式化时间
        SerializeConfig mapping = new SerializeConfig();
        mapping.put(Date.class, new SimpleDateFormatSerializer(
               "yyyy-MM-dd HH:mm:ss"));

        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //  fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        fastJsonConfig.setSerializeConfig(mapping);
        fastConverter.setFastJsonConfig(fastJsonConfig);
        HttpMessageConverter<?> converter = fastConverter;
        return new HttpMessageConverters(converter);
    }

}

3. Spring Boot集成分布插件Pagehelper

以上的功能实现了简单的mybatis应用。但是涉及到数据库的查询,不可避免需要使用到分页。这里我推荐pagehelper插件实现分页功能

3.1. pom.xml

引入相关的jar

<!-- 分布插件 -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.1</version>
</dependency>
<!-- Spring Boot集成 pagehelper-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.1</version>
</dependency>

3.2. 分页相关的辅助类

MyPage







请到「今天看啥」查看全文


推荐文章
世纪风云潮  ·  邹衍的大九州说
7 年前
21世纪经济报道  ·  鲜为人知的情趣经济:被低估的百亿市场
7 年前
建筑师的非建筑  ·  古代文人用的纸,竟然这样美!
7 年前
InternetDeep  ·  2017年中国稀土集团排行榜
7 年前