spring boot 1.5.4 整合 mybatis(十二)

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

Spring Boot集成Mybatis有两种方式:

 

方式一:传统的引入外部资源配置的方式,方便对mybatis的控制;

方式二:mybatis官方提供spring-boot整合的方式。

 

这里,还是使用UserMapper类和userMapper.xml文件分离的做法。关于mapper.xmlsql语句可以直接集成到Mapper接口中。详见第4章节:将SQL语句集成到UserMapper接口类中

 

1      方式一:整合mybatis资源

1.1    新建spring-boot-mybatis项目

spring-boot-mybatis项目源码地址:

spring-boot相关项目源码,

码云地址:https://git.oschina.net/wyait/springboot1.5.4.git

github地址https://github.com/wyait/spring-boot-1.5.4.git


项目整体结构:

wKioL1nNqVCAi8xuAABEF4cxZ-w299.png

1.2    pom.xml  

<projectxmlns="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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>

   <parent>

      <!--spring boot项目的parent -->

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-parent</artifactId>

      <version>1.5.4.RELEASE</version>

   </parent>

   <groupId>com.wyait.boot</groupId>

   <artifactId>spring-boot-mybatis</artifactId>

   <version>0.0.1-SNAPSHOT</version>

   <packaging>war</packaging>

   <dependencies>

      <dependency>

        <!--spring boot 引入Web模块。自动配置:tomcatspringmvcjackson -->

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-web</artifactId>

        <exclusions>

           <exclusion>

              <artifactId>spring-boot-starter-logging</artifactId>

              <groupId>org.springframework.boot</groupId>

           </exclusion>

        </exclusions>

      </dependency>

      <dependency>

        <!--spring-boot整合mybatis-->

        <groupId>org.mybatis.spring.boot</groupId>

        <artifactId>mybatis-spring-boot-starter</artifactId>

        <version>1.1.1</version>

      </dependency>

      <dependency>

        <groupId>mysql</groupId>

        <artifactId>mysql-connector-java</artifactId>

      </dependency>

      <!--MyBatis提供了拦截器接口,我们可以实现自己的拦截器,将其作为一个plugin装入到SqlSessionFactory中。 Github上有位开发者写了一个分页插件,我觉得使用起来还可以,挺方便的。

        Github项目地址:https://github.com/pagehelper/Mybatis-PageHelper -->

      <dependency>

        <groupId>com.github.pagehelper</groupId>

        <artifactId>pagehelper</artifactId>

        <version>4.1.0</version>

      </dependency>

      <!--tomcat 的支持. -->

      <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-tomcat</artifactId>

        <!--添加<scope>provided</scope>,因为provided表明该包只在编译和测试的时候用 -->

        <scope>provided</scope>

      </dependency>

      <dependency>

        <!--jsp页面支持 -->

        <groupId>org.apache.tomcat.embed</groupId>

        <artifactId>tomcat-embed-jasper</artifactId>

        <scope>provided</scope>

      </dependency>

      <dependency>

        <groupId>javax.servlet</groupId>

        <artifactId>jstl</artifactId>

      </dependency>

      <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-log4j</artifactId>

        <!--这里需要指定版本,否则报错【有可能是spring-boot-1.5.4.RELEASE版本没有管理log4j版本的原因】 -->

        <version>1.3.2.RELEASE</version>

      </dependency>

 

      <!--spring boot集成Swagger2-->

      <dependency>

        <groupId>io.springfox</groupId>

        <artifactId>springfox-swagger2</artifactId>

        <version>2.6.1</version>

      </dependency>

      <dependency>

        <groupId>io.springfox</groupId>

        <artifactId>springfox-swagger-ui</artifactId>

        <version>2.6.1</version>

      </dependency>

      <!--devtools可以实现页面热部署(即页面修改后会立即生效,这个可以直接在application.properties文件中配置spring.thymeleaf.cache=false或者视图解析器设置缓存为false来实现),

        实现类文件热部署(类文件修改后不会立即生效,待编译后生效),实现对属性文件的热部署。devtools会监听classpath下的文件变动,并且会立即重启应用(发生在保存时机),注意:因为其采用的虚拟机机制,该项重启是很快的 -->

      <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-devtools</artifactId>

        <optional>true</optional>

        <!--optional=true,依赖不会传递,该项目依赖devtools;之后依赖SpringBoot1项目的项目如果想要使用devtools,需要重新引入 -->

      </dependency>

   </dependencies>

   <build>

      <plugins>

        <plugin>

           <!--配置spring bootmaven插件 -->

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-maven-plugin</artifactId>

           <!--<configuration> fork : 如果没有该项配置,devtools不会起作用,即应用不会restart【实测:可以不配置】

              <fork>true</fork></configuration> -->

        </plugin>

      </plugins>

   </build>

</project>

1.3    Application.java

// 这是一个配置Spring的配置类

@Configuration

// @SpringBootApplicationSpring Boot项目的核心注解,主要目的是开启自动配置,自动扫描该类同级包以及子包。

@SpringBootApplication

public class Application {

 

   publicstatic void main(String[] args) {

      //启动spring boot应用

      SpringApplicationsa = new SpringApplication(Application.class);

      //禁用devTools热部署

      System.setProperty("spring.devtools.restart.enabled","false");

      //禁用命令行更改application.properties属性

      sa.setAddCommandLineProperties(false);

      sa.run(args);

   }

}

1.4    mybatis相关配置类:集成pageHelper分页插件,并开启事务

 

@Configuration

@EnableTransactionManagement

// 开启注解事务支持

public class MybatisConfigimplements TransactionManagementConfigurer {

   //spring容器管理,可以直接注入使用

   @Autowired

   DataSourcedataSource;

 

   @Bean(name= "sqlSessionFactory")

   publicSqlSessionFactory sqlSessionFactoryBean() {

      SqlSessionFactoryBeanbean = new SqlSessionFactoryBean();

      bean.setDataSource(dataSource);

      bean.setTypeAliasesPackage("com.wyait.boot.pojo");

 

      //分页插件

      PageHelperpageHelper = new PageHelper();

      Propertiesproperties = new Properties();

      properties.setProperty("reasonable","true");

      properties.setProperty("supportMethodsArguments","true");

      properties.setProperty("returnPageInfo","check");

      properties.setProperty("params","count=countSql");

      pageHelper.setProperties(properties);

 

      //添加插件

      bean.setPlugins(newInterceptor[] { pageHelper });

 

      //添加XML目录

      ResourcePatternResolverresolver = new PathMatchingResourcePatternResolver();

      try{

        bean.setMapperLocations(resolver

              .getResources("classpath:mybatis/*.xml"));

        returnbean.getObject();

      }catch (Exception e) {

        e.printStackTrace();

        thrownew RuntimeException(e);

      }

   }

 

   @Bean

   publicSqlSessionTemplate sqlSessionTemplate(

        SqlSessionFactorysqlSessionFactory) {

      returnnew SqlSessionTemplate(sqlSessionFactory);

   }

 

   //开启注解事务

   @Bean

   @Override

   publicPlatformTransactionManager annotationDrivenTransactionManager() {

      returnnew DataSourceTransactionManager(dataSource);

   }

}

1.5    TODO 编写实体类、servicemappermapper.xml

1.6    启动,测试

TODO


 

2      方式二:mybatis整合spring-boot

mybatis-spring-boot项目源码地址

spring-boot相关项目源码,

码云地址:https://git.oschina.net/wyait/springboot1.5.4.git

github地址https://github.com/wyait/spring-boot-1.5.4.git

2.1    新建mybatis-spring-boot工程

项目结构:

wKiom1nNqZ3zPl2gAABMwU48hU0067.png

Application.java

// 这是一个配置Spring的配置类

@Configuration

// @SpringBootApplicationSpring Boot项目的核心注解,主要目的是开启自动配置,自动扫描该类同级包以及子包。

@SpringBootApplication

//@MapperScan(basePackages ="com.wyait.boot.dao")

public class Application {

 

   publicstatic void main(String[] args) {

      //启动spring boot应用

      SpringApplicationsa = new SpringApplication(Application.class);

      //禁用devTools热部署

      System.setProperty("spring.devtools.restart.enabled","false");

      //禁用命令行更改application.properties属性

      sa.setAddCommandLineProperties(false);

      sa.run(args);

   }

}

 

2.2    pom.xml

<projectxmlns="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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>

   <parent>

      <!--spring boot项目的parent -->

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-parent</artifactId>

      <version>1.5.4.RELEASE</version>

   </parent>

   <groupId>com.wyait.mybatis</groupId>

   <artifactId>mybatis-spring-boot</artifactId>

   <version>0.0.1-SNAPSHOT</version>

   <packaging>war</packaging>

   <dependencies>

      <dependency>

        <!--spring boot 引入Web模块。自动配置:tomcatspringmvcjackson -->

         <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-web</artifactId>

        <exclusions>

           <exclusion>

              <artifactId>spring-boot-starter-logging</artifactId>

              <groupId>org.springframework.boot</groupId>

           </exclusion>

         </exclusions>

      </dependency>

      <dependency>

        <!--spring-boot整合mybatis-->

        <groupId>org.mybatis.spring.boot</groupId>

        <artifactId>mybatis-spring-boot-starter</artifactId>

        <version>1.1.1</version>

      </dependency>

      <dependency>

        <groupId>mysql</groupId>

        <artifactId>mysql-connector-java</artifactId>

      </dependency>

      <dependency>

      <!--pageHelper分页插件 -->

        <groupId>com.github.pagehelper</groupId>

        <artifactId>pagehelper-spring-boot-starter</artifactId>

        <version>1.1.1</version>

      </dependency>

      <!-- MyBatis提供了拦截器接口,我们可以实现自己的拦截器,将其作为一个plugin装入到SqlSessionFactory中。 Github上有位开发者写了一个分页插件,我觉得使用起来还可以,挺方便的。

        Github项目地址:https://github.com/pagehelper/Mybatis-PageHelper -->

      <!--<dependency>

        <groupId>com.github.pagehelper</groupId>

        <artifactId>pagehelper</artifactId>

        <version>4.1.0</version>

      </dependency>-->

      <!--tomcat 的支持. -->

      <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-tomcat</artifactId>

        <!--添加<scope>provided</scope>,因为provided表明该包只在编译和测试的时候用 -->

        <scope>provided</scope>

      </dependency>

      <dependency>

        <!--jsp页面支持 -->

        <groupId>org.apache.tomcat.embed</groupId>

        <artifactId>tomcat-embed-jasper</artifactId>

        <scope>provided</scope>

      </dependency>

      <dependency>

        <groupId>javax.servlet</groupId>

        <artifactId>jstl</artifactId>

      </dependency>

      <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-log4j</artifactId>

        <!--这里需要指定版本,否则报错【有可能是spring-boot-1.5.4.RELEASE版本没有管理log4j版本的原因】 -->

        <version>1.3.2.RELEASE</version>

      </dependency>

 

      <!--spring boot集成Swagger2-->

      <dependency>

        <groupId>io.springfox</groupId>

        <artifactId>springfox-swagger2</artifactId>

        <version>2.6.1</version>

      </dependency>

      <dependency>

        <groupId>io.springfox</groupId>

        <artifactId>springfox-swagger-ui</artifactId>

        <version>2.6.1</version>

      </dependency>

      <!--devtools可以实现页面热部署(即页面修改后会立即生效,这个可以直接在application.properties文件中配置spring.thymeleaf.cache=false或者视图解析器设置缓存为false来实现),

        实现类文件热部署(类文件修改后不会立即生效,待编译后生效),实现对属性文件的热部署。devtools会监听classpath下的文件变动,并且会立即重启应用(发生在保存时机),注意:因为其采用的虚拟机机制,该项重启是很快的 -->

      <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-devtools</artifactId>

        <optional>true</optional>

        <!--optional=true,依赖不会传递,该项目依赖devtools;之后依赖SpringBoot1项目的项目如果想要使用devtools,需要重新引入 -->

      </dependency>

   </dependencies>

   <build>

      <plugins>

        <plugin>

           <!--配置spring bootmaven插件 -->

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-maven-plugin</artifactId>

           <!--<configuration> fork : 如果没有该项配置,devtools不会起作用,即应用不会restart【实测:可以不配置】

              <fork>true</fork></configuration> -->

        </plugin>

      </plugins>

   </build>

</project>

2.3    application.properties配置:集成pageHelper,指定mapper.xml路径

# mysql

spring.datasource.url=jdbc:mysql://localhost:3306/test

spring.datasource.username=root

spring.datasource.password=123456

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

使用druid连接池  需要注意的是:spring.datasource.type旧的spring boot版本是不能识别的。

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# mybatis

mybatis.type-aliases-package=com.wyait.boot.pojo

mybatis.mapper-locations=classpath:mapper/*.xml

通用mapper配置

#mapper.mappers=com.wyait.boot.dao

#mapper.not-empty=false

#mapper.identity=MYSQL

# pagehelper

pagehelper.helperDialect=mysql

pagehelper.reasonable=true

pagehelper.supportMethodsArguments=true

pagehelper.returnPageInfo=check

pagehelper.params=count=countSql

2.4    UserMapper

TODO 详见项目

mybatis-spring-boot项目源码地址:https://git.oschina.net/wyait/springboot1.5.4.git


在接口上添加@Mapper注解即可或者在Application上添加扫描:@MapperScan(basePackages = "com.wyait.boot.dao")

2.5    启动,测试结果

wKiom1nNqazwtE-3AAC5wRqZyxM274.png

3      SQL语句集成到UserMapperXML接口类中

写法:

@Mapper

public interface UserMapperXML {

  @Select("SELECT * FROM USERWHERE NAME = #{name}")

  public UserfindUser(@Param("name") String name);

 

  @Select("SELECT * FROMUSER")

  public List<User>findAllUser();

 

  /**

   *

   * @描述:更新用户信息

   * @创建人:wyait

   * @创建时间:2017629下午1:33:09

   * @param user

   * @return

   */

  @Update("update user setage=#{age} where id=#{id}")

  public int update(User user);

}

 

更多用法可进行百度。

4      总结

项目:mybatis-spring-boot整合了Mapper接口分离Sqlxml中的写法和注解sql写法。详见项目源码。




本文转自 wyait 51CTO博客,原文链接:http://blog.51cto.com/wyait/1969626,如需转载请自行联系原作者
相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
27天前
|
Java 应用服务中间件 Maven
SpringBoot 项目瘦身指南
SpringBoot 项目瘦身指南
41 0
|
1月前
|
前端开发 Java 关系型数据库
SpringBoot+MyBatis 天猫商城项目
SpringBoot+MyBatis 天猫商城项目
55 1
|
1月前
|
SQL Java 数据库连接
springboot中配置mybatis别名该怎么写?
springboot中配置mybatis别名该怎么写?
32 0
|
1月前
|
XML Java 关系型数据库
【SpringBoot系列】SpringBoot集成Fast Mybatis
【SpringBoot系列】SpringBoot集成Fast Mybatis
|
1月前
|
SQL JavaScript Java
springboot+springm vc+mybatis实现增删改查案例!
springboot+springm vc+mybatis实现增删改查案例!
26 0
|
16天前
|
SQL Java 数据库连接
【mybatis】第一篇,Springboot中使用插件PageHelper不生效解决方案
【mybatis】第一篇,Springboot中使用插件PageHelper不生效解决方案
|
7天前
|
安全 Java 应用服务中间件
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
24 0
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
|
9天前
|
XML Java C++
【Spring系列】Sping VS Sping Boot区别与联系
【4月更文挑战第2天】Spring系列第一课:Spring Boot 能力介绍及简单实践
【Spring系列】Sping VS Sping Boot区别与联系
|
13天前
|
Java 关系型数据库 MySQL
整合SpringBoot与MyBatis时报错时区异常
整合SpringBoot与MyBatis时报错时区异常
14 0
|
16天前
|
存储 关系型数据库 MySQL
【mybatis-plus】Springboot+AOP+自定义注解实现多数据源操作(数据源信息存在数据库)
【mybatis-plus】Springboot+AOP+自定义注解实现多数据源操作(数据源信息存在数据库)