spingBoot整合mybatis+generator+pageHelper
环境/版本一览:
- 开发工具:Intellij IDEA 2018.1.4
- springboot: 2.0.4.RELEASE
- jdk:1.8.0_40
- maven:3.3.9
- alibaba Druid 数据库连接池:1.1.9
额外功能:
- PageHelper 分页插件
- mybatis generator 自动生成代码插件
开始搭建:
创建项目:
看一下文件结构:
查看一下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.denwgei</groupId> <artifactId>springbootmybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springbootmybatis</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.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-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</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.5</version> </dependency> <!-- alibaba的druid数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.9</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.2</version> <configuration> <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> </plugin> </plugins> </build> </project>
项目不使用application.properties文件 而使用更加简洁的application.yml文件:
将原有的resource文件夹下的application.properties文件删除,创建一个新的application.yml配置文件,
文件的内容如下:
注意application.yml 要放在resource的一级目录下,否则会找不到,报错。
application.yml
server: port: 8080 spring: datasource: name: mysql_test type: com.alibaba.druid.pool.DruidDataSource #druid相关配置 druid: #监控统计拦截的filters filters: stat driver-class-name: com.mysql.jdbc.Driver #基本属性 url: jdbc:mysql://127.0.0.1:3306/floor_shop username: root password: admin #配置初始化大小/最小/最大 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 ## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别 mybatis: mapper-locations: classpath:mapper/*.xml #注意:一定要对应mapper映射xml文件的所在路径 type-aliases-package: com.springbootdemo3.sbmybatis.model # 注意:对应实体类的路径 #pagehelper pagehelper: helperDialect: mysql reasonable: true supportMethodsArguments: true params: count=countSql returnPageInfo: check
使用mybatis generator 自动生成代码:
- 配置pom.xml中generator 插件所对应的配置文件 ${basedir}/src/main/resources/generator/generatorConfig.xml
generatorConfig.xml :
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE generatorConfiguration 3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> 5 <generatorConfiguration> 6 <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包--> 7 <classPathEntry location="F:libmybatismysql-connector-java-5.1.11.jar"/> 8 <context id="DB2Tables" targetRuntime="MyBatis3"> 9 <commentGenerator> 10 <property name="suppressDate" value="true"/> 11 <!-- 是否去除自动生成的注释 true:是 : false:否 --> 12 <property name="suppressAllComments" value="true"/> 13 </commentGenerator> 14 <!--数据库链接URL,用户名、密码 --> 15 <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/floor_shop" 16 userId="root" password="admin"> 17 </jdbcConnection> 18 <javaTypeResolver> 19 <property name="forceBigDecimals" value="false"/> 20 </javaTypeResolver> 21 <!-- 生成模型的包名和位置--> 22 <javaModelGenerator targetPackage="com.denwgei.springbootmybatis.model" targetProject="src/main/java"> 23 <property name="enableSubPackages" value="true"/> 24 <property name="trimStrings" value="true"/> 25 </javaModelGenerator> 26 <!-- 生成映射文件的包名和位置--> 27 <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"> 28 <property name="enableSubPackages" value="true"/> 29 </sqlMapGenerator> 30 <!-- 生成DAO的包名和位置--> 31 <javaClientGenerator type="XMLMAPPER" targetPackage="com.denwgei.springbootmybatis.Dao" targetProject="src/main/java"> 32 <property name="enableSubPackages" value="true"/> 33 </javaClientGenerator> 34 <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名(model)--> 35 <table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" 36 enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> 37 </context> 38 </generatorConfiguration>
- 点击run-Edit Configurations
运行 :
注意!!!同一张表一定不要运行多次,因为mapper的映射文件中会生成多次的代码,导致报错,切记
最后生成的文件及结构:
UserMapper:
1 package com.denwgei.springbootmybatis.Dao; 2 3 import com.denwgei.springbootmybatis.model.User; 4 5 public interface UserMapper { 6 int deleteByPrimaryKey(Integer id); 7 8 int insert(User record); 9 10 int insertSelective(User record); 11 12 User selectByPrimaryKey(Integer id); 13 14 int updateByPrimaryKeySelective(User record); 15 16 int updateByPrimaryKey(User record);
//自己加的
public List<User> queryAll();
17 }
User :
1 package com.denwgei.springbootmybatis.model; 2 3 import java.util.Date; 4 5 public class User { 6 private Integer id; 7 8 private Integer userId; 9 10 private String userName; 11 12 private String passWord; 13 14 private String state; 15 16 private String type; 17 18 private Date updateTime; 19 20 private Date createTime; 21 22 public Integer getId() { 23 return id; 24 } 25 26 public void setId(Integer id) { 27 this.id = id; 28 } 29 30 public Integer getUserId() { 31 return userId; 32 } 33 34 public void setUserId(Integer userId) { 35 this.userId = userId; 36 } 37 38 public String getUserName() { 39 return userName; 40 } 41 42 public void setUserName(String userName) { 43 this.userName = userName == null ? null : userName.trim(); 44 } 45 46 public String getPassWord() { 47 return passWord; 48 } 49 50 public void setPassWord(String passWord) { 51 this.passWord = passWord == null ? null : passWord.trim(); 52 } 53 54 public String getState() { 55 return state; 56 } 57 58 public void setState(String state) { 59 this.state = state == null ? null : state.trim(); 60 } 61 62 public String getType() { 63 return type; 64 } 65 66 public void setType(String type) { 67 this.type = type == null ? null : type.trim(); 68 } 69 70 public Date getUpdateTime() { 71 return updateTime; 72 } 73 74 public void setUpdateTime(Date updateTime) { 75 this.updateTime = updateTime; 76 } 77 78 public Date getCreateTime() { 79 return createTime; 80 } 81 82 public void setCreateTime(Date createTime) { 83 this.createTime = createTime; 84 } 85 }
UserMapper.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.dengwei.day01springboot.dao.UserMapper" > <resultMap id="BaseResultMap" type="com.dengwei.day01springboot.model.User" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="user_id" property="userId" jdbcType="INTEGER" /> <result column="user_name" property="userName" jdbcType="VARCHAR" /> <result column="pass_word" property="passWord" jdbcType="VARCHAR" /> <result column="state" property="state" jdbcType="VARCHAR" /> <result column="type" property="type" jdbcType="VARCHAR" /> <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" /> <result column="create_time" property="createTime" jdbcType="TIMESTAMP" /> </resultMap> <sql id="Base_Column_List" > id, user_id, user_name, pass_word, state, type, update_time, create_time </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from user where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from user where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.dengwei.day01springboot.model.User" > insert into user (id, user_id, user_name, pass_word, state, type, update_time, create_time) values (#{id,jdbcType=INTEGER}, #{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{passWord,jdbcType=VARCHAR}, #{state,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, #{updateTime,jdbcType=TIMESTAMP}, #{createTime,jdbcType=TIMESTAMP}) </insert> <insert id="insertSelective" parameterType="com.dengwei.day01springboot.model.User" > insert into user <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="userId != null" > user_id, </if> <if test="userName != null" > user_name, </if> <if test="passWord != null" > pass_word, </if> <if test="state != null" > state, </if> <if test="type != null" > type, </if> <if test="updateTime != null" > update_time, </if> <if test="createTime != null" > create_time, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="userId != null" > #{userId,jdbcType=INTEGER}, </if> <if test="userName != null" > #{userName,jdbcType=VARCHAR}, </if> <if test="passWord != null" > #{passWord,jdbcType=VARCHAR}, </if> <if test="state != null" > #{state,jdbcType=VARCHAR}, </if> <if test="type != null" > #{type,jdbcType=VARCHAR}, </if> <if test="updateTime != null" > #{updateTime,jdbcType=TIMESTAMP}, </if> <if test="createTime != null" > #{createTime,jdbcType=TIMESTAMP}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.dengwei.day01springboot.model.User" > update user <set > <if test="userId != null" > user_id = #{userId,jdbcType=INTEGER}, </if> <if test="userName != null" > user_name = #{userName,jdbcType=VARCHAR}, </if> <if test="passWord != null" > pass_word = #{passWord,jdbcType=VARCHAR}, </if> <if test="state != null" > state = #{state,jdbcType=VARCHAR}, </if> <if test="type != null" > type = #{type,jdbcType=VARCHAR}, </if> <if test="updateTime != null" > update_time = #{updateTime,jdbcType=TIMESTAMP}, </if> <if test="createTime != null" > create_time = #{createTime,jdbcType=TIMESTAMP}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.dengwei.day01springboot.model.User" > update user set user_id = #{userId,jdbcType=INTEGER}, user_name = #{userName,jdbcType=VARCHAR}, pass_word = #{passWord,jdbcType=VARCHAR}, state = #{state,jdbcType=VARCHAR}, type = #{type,jdbcType=VARCHAR}, update_time = #{updateTime,jdbcType=TIMESTAMP}, create_time = #{createTime,jdbcType=TIMESTAMP} where id = #{id,jdbcType=INTEGER} </update> </mapper>
项目启动类:
package com.denwgei.springbootmybatis;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.denwgei.springbootmybatis.Dao")
public class SpringbootmybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootmybatisApplication.class, args);
}
}
注意:@MapperScan("com.winter.mapper")
这个注解非常的关键,这个对应了项目中mapper(dao)所对应的包路径,很多同学就是这里忘了加导致异常的
新建service层 :
IUserService :
1 package com.denwgei.springbootmybatis.service;
2
3 import com.denwgei.springbootmybatis.model.User;
4 import com.github.pagehelper.PageInfo;
5
6 public interface IUserService {
7 public PageInfo<User> queryAll(int pageNum, int pageSize);
8 }
impl :UserService :
1 package com.denwgei.springbootmybatis.service.impl; 2 3 import com.denwgei.springbootmybatis.Dao.IUserMapper; 4 import com.denwgei.springbootmybatis.model.User; 5 import com.denwgei.springbootmybatis.service.IUserService; 6 import com.github.pagehelper.PageHelper; 7 import com.github.pagehelper.PageInfo; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.stereotype.Service; 10 11 import java.util.List; 12 @Service 13 public class UserService implements IUserService { 14 @Autowired //或则@Resource 15 private IUserMapper userMapper; //这里报错是正常的 16 17 /* 18 * 这个方法中用到了我们开头配置依赖的分页插件pagehelper 19 * 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可; 20 * pageNum 开始页数 21 * pageSize 每页显示的数据条数 22 * */ 23 @Override 24 public PageInfo<User> queryAll(int pageNum, int pageSize) { 25 //将参数传给这个方法就可以实现物理分页了,非常简单。 26 PageHelper.startPage(pageNum, pageSize); 27 List<User> users = userMapper.queryAll(); 28 PageInfo result = new PageInfo(users); 29 return result; 30 } 31 }
userController :
1 package com.denwgei.springbootmybatis.Controller; 2 3 import com.denwgei.springbootmybatis.model.User; 4 import com.denwgei.springbootmybatis.service.impl.UserService; 5 import com.github.pagehelper.PageInfo; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Controller; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 import org.springframework.web.bind.annotation.ResponseBody; 10 11 @Controller 12 @RequestMapping("/user") 13 public class UserController { 14 @Autowired 15 // @Resource 16 private UserService userService; 17 @RequestMapping("/allUser") 18 @ResponseBody 19 public PageInfo<User> queryAllUser(){ 20 PageInfo<User> userPageInfo = userService.queryAll(1, 3); 21 return userPageInfo; 22 } 23
启动springBoot的启动程序:
启动成功:
好的,试试吧!!!!