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  :

 <?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="F:\lib\mybatis\mysql-connector-java-5.1.11.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/floor_shop"
userId="root" password="admin">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.denwgei.springbootmybatis.model" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.denwgei.springbootmybatis.Dao" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名(model)-->
<table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
  • 点击run-Edit Configurations

运行 :
注意!!!同一张表一定不要运行多次,因为mapper的映射文件中会生成多次的代码,导致报错,切记

最后生成的文件及结构:

UserMapper:

 package com.denwgei.springbootmybatis.Dao;

 import com.denwgei.springbootmybatis.model.User;

 public interface UserMapper {
int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record);
//自己加的
public List<User> queryAll();
 }

User :

 package com.denwgei.springbootmybatis.model;

 import java.util.Date;

 public class User {
private Integer id; private Integer userId; private String userName; private String passWord; private String state; private String type; private Date updateTime; private Date createTime; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public Integer getUserId() {
return userId;
} public void setUserId(Integer userId) {
this.userId = userId;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
} public String getPassWord() {
return passWord;
} public void setPassWord(String passWord) {
this.passWord = passWord == null ? null : passWord.trim();
} public String getState() {
return state;
} public void setState(String state) {
this.state = state == null ? null : state.trim();
} public String getType() {
return type;
} public void setType(String type) {
this.type = type == null ? null : type.trim();
} public Date getUpdateTime() {
return updateTime;
} public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}

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  :

 package com.denwgei.springbootmybatis.service;

 import com.denwgei.springbootmybatis.model.User;
import com.github.pagehelper.PageInfo; public interface IUserService {
public PageInfo<User> queryAll(int pageNum, int pageSize);
}

impl :UserService :

 package com.denwgei.springbootmybatis.service.impl;

 import com.denwgei.springbootmybatis.Dao.IUserMapper;
import com.denwgei.springbootmybatis.model.User;
import com.denwgei.springbootmybatis.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List;
@Service
public class UserService implements IUserService {
@Autowired //或则@Resource
private IUserMapper userMapper; //这里报错是正常的 /*
* 这个方法中用到了我们开头配置依赖的分页插件pagehelper
* 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可;
* pageNum 开始页数
* pageSize 每页显示的数据条数
* */
@Override
public PageInfo<User> queryAll(int pageNum, int pageSize) {
//将参数传给这个方法就可以实现物理分页了,非常简单。
PageHelper.startPage(pageNum, pageSize);
List<User> users = userMapper.queryAll();
PageInfo result = new PageInfo(users);
return result;
}
}

userController  :

 package com.denwgei.springbootmybatis.Controller;

 import com.denwgei.springbootmybatis.model.User;
import com.denwgei.springbootmybatis.service.impl.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
@RequestMapping("/user")
public class UserController {
@Autowired
// @Resource
private UserService userService;
@RequestMapping("/allUser")
@ResponseBody
public PageInfo<User> queryAllUser(){
PageInfo<User> userPageInfo = userService.queryAll(1, 3);
return userPageInfo;
}

启动springBoot的启动程序:

启动成功:

好的,试试吧!!!!

spingBoot整合mybatis+generator+pageHelper的更多相关文章

  1. SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件

    原文链接 我们这一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池 ...

  2. SpringBoot整合mybatis使用pageHelper插件进行分页操作

    SpringBoot整合mybatis分页操作 SpringBoot整合Mybatis进行分页操作,这里需要使用Mybatis的分页插件:pageHelper, 关于pageHelper的介绍,请查看 ...

  3. springboot 整合mybatis,pagehelper。测试类。

    报名立减200元.暑假直降6888. 遇到的异常. 1.这是在使用mybatis成功连接数据库后,通过service层调用dao层出现的异常. 异常原因:在启动类上面的注解@MapperScan没有指 ...

  4. springboot整合mybatis+generator

    源码地址:springboot-integration 如果你觉得解决了你使用的需求,欢迎fork|star.

  5. springboot整合mybatis通用Mapper

    参考: https://blog.csdn.net/x18707731829/article/details/82814095 https://www.jianshu.com/p/6d2103451d ...

  6. 项目脚手架 - 《Spring Boot + MyBatis + MyBatis Generator》

    前言 最近启动了一个新的项目发现,每当一个新项目的启动往往需要从头搭建一个"框架",其中虽然很多基础代码可以Copy,但也会浪费不少时间. 基于这个情况,我打算在GitHub上创建 ...

  7. springboot学习随笔(四):Springboot整合mybatis(含generator自动生成代码)

    这章我们将通过springboot整合mybatis来操作数据库 以下内容分为两部分,一部分主要介绍generator自动生成代码,生成model.dao层接口.dao接口对应的sql配置文件 第一部 ...

  8. Spring Boot整合tk.mybatis及pageHelper分页插件及mybatis逆向工程

    Spring Boot整合druid数据源 1)引入依赖 <dependency> <groupId>com.alibaba</groupId> <artif ...

  9. springboot使用之二:整合mybatis(xml方式)并添加PageHelper插件

    整合mybatis实在前面项目的基础上进行的,前面项目具体整合请参照springboot使用之一. 一.整合mybatis 整合mybatis的时候可以从mybatis官网下载mybatis官网整合的 ...

随机推荐

  1. tp5命令行基础介绍

    查看指令 生成模块 生成文件 生成类库映射文件 生成路由缓存文件 生成数据表字段缓存文件 指令扩展示例 命令行调试 命令行颜色支持 调用命令 查看指令 命令行工具需要在命令行下面执行,请先确保你的ph ...

  2. thusc2017

    巧克力 题目描述 "人生就像一盒巧克力,你永远不知道吃到的下一块是什么味道." 明明收到了一大块巧克力,里面有若干小块,排成

  3. 【dp】P1434 [SHOI2002]滑雪

    题目描述 Michael喜欢滑雪.这并不奇怪,因为滑雪的确很刺激.可是为了获得速度,滑的区域必须向下倾斜,而且当你滑到坡底,你不得不再次走上坡或者等待升降机来载你.Michael想知道在一个区域中最长 ...

  4. 「TJOI2015」旅游 解题报告

    「TJOI2015」旅游 LCT沙比题 考虑我们其实是在维护一条链的\(\max\limits_{i<j} v_j-v_i\) 每次直接拿左右子树更新一下就可以了 写的时候把两个方向都维护一下, ...

  5. 51nod 1443 路径和树(最短路树)

    题目链接:路径和树 题意:给定无向带权连通图,求从u开始边权和最小的最短路树,输出最小边权和. 题解:构造出最短路树,把存留下来的边权全部加起来.(跑dijkstra的时候松弛加上$ < $变成 ...

  6. luogu5024 [NOIp2018]保卫王国 (动态dp)

    可以直接套动态dp,但因为它询问之间相互独立,所以可以直接倍增记x转移到fa[x]的矩阵 #include<bits/stdc++.h> #define CLR(a,x) memset(a ...

  7. A.01.02—模块的输入—高端输入

    高端输入即一个高电平信号输入到模块,模块采样时最典型的是采用下拉电阻采样,当然,还有限流电阻和分压电阻,具体可以参见实际电路. 高端输入在汽车上用得不多,这种类型的输入既可以是开关提供的也可以是模块提 ...

  8. MYSQL主从复制制作配置方案

    1. 主从复制机器配置 操作系统:centos7 x64 基于vagrant下的virtual box的虚拟机两台 master ip:192.168.21.11, slave ip 192.168. ...

  9. 【P2303】Longge的问题

    题目大意:求\[\sum\limits_{i=1}^ngcd(n,i)\] 题解:发现 gcd 中有很多是重复的,因此考虑枚举 gcd. \[\sum\limits_{i=1}^ngcd(n,i)=\ ...

  10. 【洛谷P3810】陌上花开

    题目大意:给定一个三维空间点的坐标,求对于任意一个点三维均小于等于这个点的点个数. 题解:学会了简单的 cdq 分治. 首先,先将第一维从小到大排序,再用类似归并排序的操作对第二维进行排序,在第二维合 ...