本介绍Spring Boot2.0整合Mybatis,通过MyBatis Generator插件自动生成mapper的sql注解及Provider类的过程,支持多环境的yml配置文件
首先用IDE开发工具(IDEA,STS,Eclipse)创建一个Spring Boot工程springboot-mybatis-demo-annotation, pom.xml如下
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.fhbean.springboot</groupId> <artifactId>springboot-mybatis-demo-annotation</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot-mybatis-demo-annotation</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!-- spring jpa spring jpa中带有自带的tomcat数据连接池; 在代码中我们也需要用到. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- alibaba的druid数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.11</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-joda</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-parameter-names</artifactId> </dependency> <!-- 分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.3</version> </dependency> <!-- alibaba的druid数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- mybatis generator 自动生成代码插件 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.6</version> <configuration> <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> </plugin> </plugins> </build> </project>
创建数据库springboot,采用utf-8字符集,并创建表t_user
CREATE TABLE `t_user` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `phone` varchar(255) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;在项目的/src/main/resources/generator下,创建一个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> <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包--> <classPathEntry location="D:/javaResources/apache/maven2-repository/mysql/mysql-connector-java/5.1.45/mysql-connector-java-5.1.45.jar"/> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--数据库链接URL,用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/springboot" userId="root" password="root"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成模型的包名和位置--> <javaModelGenerator targetPackage="com.fhbean.springboot.mybatisdemo.model" targetProject="springboot-mybatis-demo-annotation/src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成映射文件的包名和位置--> <sqlMapGenerator targetPackage="mapping" targetProject="springboot-mybatis-demo-annotation/src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 生成DAO的包名和位置--> <!-- XMLMAPPER生成xml映射文件, ANNOTATEDMAPPER生成的dao采用注解来写sql --> <javaClientGenerator type="ANNOTATEDMAPPER" targetPackage="com.fhbean.springboot.mybatisdemo.mapper" targetProject="springboot-mybatis-demo-annotation/src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名--> <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
注意这里的配置:
<javaClientGenerator type="ANNOTATEDMAPPER" targetPackage="com.fhbean.springboot.mybatisdemo.mapper" targetProject="springboot-mybatis-demo-annotation/src/main/java">
type的值是XMLMAPPER,则生成xml映射文件;是ANNOTATEDMAPPER,则生成的dao采用注解来写sql。
application.yml
debug: false mybatis: mapper-locations: classpath:mapping/*.xml type-aliases-package: com.fhbean.springboot.mybatisdemo.model #pagehelper分页插件 pagehelper: helperDialect: mysql reasonable: true supportMethodsArguments: true params: count=countSql spring: profiles: active: dev
application-dev.yml
server: port: 8080 spring: profiles: dev datasource: name: test url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true username: root password: root # 使用druid数据源 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20若是采用STS或Eclipse,则安装一个MyBatis Generator插件[Help] --> [Eclipse Marketplace]
右键generatorConfig.xml,在弹出菜单选择[Run As] --> [Run MyBatis Generator]
随后在com.fhbean.springboot.mybatisdemo.model包下,生成一个名为User的JavaBean
public class User { private Integer userId; private String userName; private String password; private String phone; .... }
在com.fhbean.springboot.mybatisdemo.mapper包下,会生成一个接口UserMapper和一个类UserSqlProvider
UserMapper内容如下:
package com.fhbean.springboot.mybatisdemo.mapper; import com.fhbean.springboot.mybatisdemo.model.User; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.InsertProvider; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.apache.ibatis.annotations.UpdateProvider; import org.apache.ibatis.type.JdbcType; public interface UserMapper { @Delete({ "delete from t_user", "where user_id = #{userId,jdbcType=INTEGER}" }) int deleteByPrimaryKey(Integer userId); @Insert({ "insert into t_user (user_id, user_name, ", "password, phone)", "values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, ", "#{password,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR})" }) int insert(User record); @InsertProvider(type=UserSqlProvider.class, method="insertSelective") int insertSelective(User record); @Select({ "select", "user_id, user_name, password, phone", "from t_user", "where user_id = #{userId,jdbcType=INTEGER}" }) @Results({ @Result(column="user_id", property="userId", jdbcType=JdbcType.INTEGER, id=true), @Result(column="user_name", property="userName", jdbcType=JdbcType.VARCHAR), @Result(column="password", property="password", jdbcType=JdbcType.VARCHAR), @Result(column="phone", property="phone", jdbcType=JdbcType.VARCHAR) }) User selectByPrimaryKey(Integer userId); @Select({ "select", "user_id, user_name, password, phone", "from t_user" }) @Results({ @Result(column="user_id", property="userId", jdbcType=JdbcType.INTEGER, id=true), @Result(column="user_name", property="userName", jdbcType=JdbcType.VARCHAR), @Result(column="password", property="password", jdbcType=JdbcType.VARCHAR), @Result(column="phone", property="phone", jdbcType=JdbcType.VARCHAR) }) public List<User> selectAllUser(); @UpdateProvider(type=UserSqlProvider.class, method="updateByPrimaryKeySelective") int updateByPrimaryKeySelective(User record); @Update({ "update t_user", "set user_name = #{userName,jdbcType=VARCHAR},", "password = #{password,jdbcType=VARCHAR},", "phone = #{phone,jdbcType=VARCHAR}", "where user_id = #{userId,jdbcType=INTEGER}" }) int updateByPrimaryKey(User record); }其中selectAllUser()是我手工加上去的。
UserSqlProvider
package com.fhbean.springboot.mybatisdemo.mapper; import com.fhbean.springboot.mybatisdemo.model.User; import org.apache.ibatis.jdbc.SQL; public class UserSqlProvider { public String insertSelective(User record) { SQL sql = new SQL(); sql.INSERT_INTO("t_user"); if (record.getUserId() != null) { sql.VALUES("user_id", "#{userId,jdbcType=INTEGER}"); } if (record.getUserName() != null) { sql.VALUES("user_name", "#{userName,jdbcType=VARCHAR}"); } if (record.getPassword() != null) { sql.VALUES("password", "#{password,jdbcType=VARCHAR}"); } if (record.getPhone() != null) { sql.VALUES("phone", "#{phone,jdbcType=VARCHAR}"); } return sql.toString(); } public String updateByPrimaryKeySelective(User record) { SQL sql = new SQL(); sql.UPDATE("t_user"); if (record.getUserName() != null) { sql.SET("user_name = #{userName,jdbcType=VARCHAR}"); } if (record.getPassword() != null) { sql.SET("password = #{password,jdbcType=VARCHAR}"); } if (record.getPhone() != null) { sql.SET("phone = #{phone,jdbcType=VARCHAR}"); } sql.WHERE("user_id = #{userId,jdbcType=INTEGER}"); return sql.toString(); } }
UserMapper中,所有的动态SQL,都定义在类UserSqlProvider中。若要增加新的动态SQL,只需在UserSqlProvider中增加相应的方法,并在UserMapper中增加相应的引用即可,如:@UpdateProvider(type=UserSqlProvider.class, method="updateByPrimaryKeySelective")。
给SpringbootMybatisDemoAnnotationApplication增加注解@MapperScan
package com.fhbean.springboot.mybatisdemo; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.fhbean.springboot.mybatisdemo.mapper") public class SpringbootMybatisDemoAnnotationApplication { public static void main(String[] args) { SpringApplication.run(SpringbootMybatisDemoAnnotationApplication.class, args); } }
编写UserController
package com.fhbean.springboot.mybatisdemo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.fhbean.springboot.mybatisdemo.model.User; import com.fhbean.springboot.mybatisdemo.service.UserService; @Controller @RequestMapping(value = "/user") public class UserController { @Autowired private UserService userService; @ResponseBody @RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"}) public int addUser(User user) { return userService.addUser(user); } @ResponseBody @RequestMapping(value = "/all/{pageNum}/{pageSize}", produces = "application/json;charset=UTF-8") public Object findAllUser(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize) { return userService.findAllUser(pageNum, pageSize); } }
编写接口UserService
package com.fhbean.springboot.mybatisdemo.service; import java.util.List; import com.fhbean.springboot.mybatisdemo.model.User; public interface UserService { int addUser(User user); List<User> findAllUser(int pageNum, int pageSize); }编写接口的实现类UserServiceImpl,UserMapper自动注入
package com.fhbean.springboot.mybatisdemo.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fhbean.springboot.mybatisdemo.mapper.UserMapper; import com.fhbean.springboot.mybatisdemo.model.User; import com.fhbean.springboot.mybatisdemo.service.UserService; import com.github.pagehelper.PageHelper; @Service(value = "userService") public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public int addUser(User user) { return userMapper.insertSelective(user); } /* * 这个方法中用到了我们开头配置依赖的分页插件pagehelper * 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可; * pageNum 开始页数 * pageSize 每页显示的数据条数 * */ @Override public List<User> findAllUser(int pageNum, int pageSize) { //将参数传给这个方法就可以实现物理分页了,非常简单。 PageHelper.startPage(pageNum, pageSize); return userMapper.selectAllUser(); } }
启动Spring Boot工程
在浏览器录入http://localhost:8080/user/add?userName=张三&password=123&phone=13012345678
录入几条记录,
http://localhost:8080/user/all/1/5
会看到先前录入成功的数据。
[{"userId":1,"userName":"zhangsan","password":"123","phone":"13012345678"},{"userId":1000,"userName":"张三","password":"123","phone":"13012345678"},{"userId":1001,"userName":"李四","password":"123","phone":"13012345678"},{"userId":1002,"userName":"王五","password":"123","phone":"13012345678"},{"userId":1003,"userName":"马六","password":"123","phone":"13012345678"}]
项目结构图:
参考:
https://blog.csdn.net/winter_chen001/article/details/77249029
https://blog.csdn.net/Winter_chen001/article/details/78622141