spring boot --- mybatis plus
公司刚开发一个ssm架构的项目,同事推荐了mybatis的一个插件,发现上手容易,高效简洁。下面是官方的文档: 传送门请进
我的demo目录:注意SpringBoot的启动类的位置
1.首先添加pom文件的依赖:
<!-- mybatis的orm插件 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-
boot-starter</artifactId>
<version>1.0.4</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.0.7</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
注意: mybatis-plus 自动的维护了mybatis以及mybatis-spring的依赖,在springboot中这三者不能同时的出现,避免版本的冲突,表示:跳进过这个坑。。。
2、application.properties 文件;
#tomcat\u7F16\u7801
server.port=8081
# salt used for generate token
token-random-salt=restyle@123
# \u6570\u636E\u6E90\u914D\u7F6E
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db_stu_crm?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
mybatis-plus.typeAliasesPackage=com.cn.restyle.entity
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
数据源的配置:
package com.cn.restyle.config;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;
/**
* 数据源配置
*/
@Configuration
public class DataSourceConfig {
@Bean(name="dataSource")
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource(){
return new DruidDataSource();
}
// 配置事物管理器
@Bean(name="transactionManager")
public DataSourceTransactionManager transactionManager(){
return new DataSourceTransactionManager(dataSource());
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
3、mybatis的配置
package com.cn.restyle.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
@Configuration
//扫描dao或者是Mapper接口
@MapperScan("com.cn.restyle.mapper*")
public class MybatisPlusConfig {
/**
* mybatis-plus 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor(){
PaginationInterceptor page = new PaginationInterceptor();
page.setDialectType("mysql");
return page;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
4、 新建一个Student 的表
package com.cn.restyle.entity;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
import com.fasterxml.jackson.annotation.JsonFormat;
@TableName("tb_student")
public class Student {
@TableId(value="id",type=IdType.AUTO)
private Integer id;
@TableField("stu_name")
private String stuName;
@TableField("stu_number")
private String stuNumber;
private Integer gender;
private Integer age;
private String password;
@TableField("stu_mobile")
private String stuMobile;
/**
* 家长姓名
*/
@TableField("par_name")
private String parName;
@TableField("par_mobile")
private String parMobile;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
@TableField("create_time")
private Date createTime;
@TableField("is_delete")
private Integer isDelete;
@TableField("role_id")
private Integer roleId;
// setter和getter方法省略
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
注意: 在这儿注解: @TableName(“tb_student”),它是指与数据库的关联,意味着表对应的数据库的表名是tb_student.
再者,另一个注解,@TableFile(exist=false),表示Student类中有的属性,而对应的属性在表中没有这样的一个字段
5、 新建dao层接口StudentMapper:
package com.cn.restyle.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.cn.restyle.entity.Student;
/**
* Student 表数据层控制接口
*/
@Repository
public interface StudentMapper extends BaseMapper<Student> {
List<Student> findAllStudent();
List<Student> findSomeColumn();
void deleteById(Integer id);
void updateByPrimarKeySelective(Student student);
void saveStudent(Student student);
List<Student> findAllStudentPage(Pagination page);
@Select("select * from tb_student where gender = #{gender}")
@Results({
@Result(column="stu_name",property="stuName"),
@Result(column="stu_mobile",property="stuMobile"),
@Result(column="stu_number",property="stuNumber"),
@Result(column="par_name",property="parName"),
@Result(column="par_mobile",property="parMobile"),
@Result(column="create_time",property="createTime")
})
List<Student> findStuByGender(Integer gender);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
注意 : 如果在xml 中不写SQL的,可以使用注解的方式在此接口当中直接写SQL,实体和数据库表字段不一致,使用@Result注解来映射
6、 新建StudentMapper的配置文件:
<?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.cn.restyle.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="com.cn.restyle.entity.Student">
<id column="id" property="id"></id>
<result column="stu_name" property="stuName"></result>
<result column="stu_mobile" property="stuMobile"></result>
<result column="stu_number" property="stuNumber"></result>
<result column="create_time" property="createTime"></result>
<result column="role_id" property="roleId"></result>
<result column="par_mobile" property="parMobile"></result>
<result column="par_name" property="parName"></result>
<result column="is_delete" property="isDelete"></result>
</resultMap>
<sql id="base_column_list">
stu_name,stu_mobile,stu_number,create_time,par_mobile,par_name
</sql>
<insert id="insertStudent" parameterType="com.cn.restyle.entity.Student">
insert into tb_student (stu_name,stu_mobile,stu_number,par_mobile,par_name)
values
(#{stuName},#{stuMobile},#{stuNumber},#{parMobile},#{parName})
</insert>
<!-- 拼接 -->
<insert id="saveStudent" parameterType="com.cn.restyle.entity.Student">
insert into tb_student
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="stuName != null">
stu_name,
</if>
<if test="stuMobile">
stu_mobile,
</if>
<if test="stuNumber">
stu_number,
</if>
<if test="roleId">
role_id,
</if>
<if test="parMobile">
par_mobile,
</if>
<if test="parName">
par_name,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="stuName != null">#{stuName},</if>
<if test="stuMobile != null">#{stuMobile},</if>
<if test="stuNumber!= null">#{stuNumber},</if>
<if test="roleId !=null">#{roleId},</if>
<if test="parMobile != null">#{parMobile},</if>
<if test="parName !=null">#{parName},</if>
</trim>
</insert>
<delete id="deleteById" parameterType="java.lang.Integer">
delete from tb_student
where id = #{id}
</delete>
<update id="updateByPrimarKeySelective" parameterType="com.cn.restyle.entity.Student">
update tb_student
<set>
<if test="stuName ! = null">
stu_name = #{stuName}
</if>
<if test="password ! =null">
password = #{password}
</if>
<if test="stuMobile ! = null">
stu_mobile = #{stuMobile}
</if>
</set>
</update>
<update id="updateByprimaryKey">
update tb_student
set
stu_name = #{stuName}
password = #{password}
stu_mobile = #{stuMobile}
</update>
<select id="findSomeColumn" resultMap="BaseResultMap">
select
<include refid="base_column_list" />
from tb_student
</select>
<select id="findAllStudent" resultMap="BaseResultMap">
select * from tb_student
</select>
<select id="findAllStudentPage" resultMap="BaseResultMap" resultType="Student">
select * from tb_student
</select>
</mapper>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
7、新建service层的类StudentService :
package com.cn.restyle.services;
import java.util.List;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.baomidou.mybatisplus.service.IService;
import com.cn.restyle.entity.Student;
public interface StudentService extends IService<Student> {
List<Student> findAllStudent();
List<Student> findSomeColumn();
void deleteById(Integer id);
void updateByPrimarKeySelective(Student student);
void saveStudent(Student student);
Page<Student> findAllStudentPage(Page<Student> page);
List<Student> findStuByGender(Integer gender);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
8、service的实现类:
package com.cn.restyle.services.impl;
import java.util.List;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.PackageHelper;
import com.cn.restyle.entity.Student;
import com.cn.restyle.mapper.StudentMapper;
import com.cn.restyle.services.StudentService;
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper,Student>
implements StudentService {
@Override
public List<Student> findAllStudent() {
// TODO Auto-generated method stub
return baseMapper.findAllStudent();
}
@Override
public List<Student> findSomeColumn() {
// TODO Auto-generated method stub
return baseMapper.findSomeColumn();
}
@Override
public void deleteById(Integer id) {
baseMapper.deleteById(id);
}
@Override
public void updateByPrimarKeySelective(Student student) {
baseMapper.updateById(student);
}
@Override
public void saveStudent(Student student) {
baseMapper.saveStudent(student);
}
@Override
public Page<Student> findAllStudentPage(Page<Student> page) {
// TODO Auto-generated method stub
page.setRecords(baseMapper.findAllStudentPage(page));
return page;
}
@Override
public List<Student> findStuByGender(Integer gender) {
// TODO Auto-generated method stub
return baseMapper.findStuByGender(gender);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
测试的Controller:
package com.cn.restyle.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cn.restyle.entity.Student;
import com.cn.restyle.services.StudentService;
import com.cn.restyle.util.Result;
import lombok.extern.slf4j.Slf4j;
@RestController
@RequestMapping("/v1/login")
@Slf4j
public class TestController {
@Autowired
private StudentService studentService;
@RequestMapping("/register")
public Result Register(@RequestBody Student student){
studentService.insert(student);
return new Result(Result.OK,"保存成功");
}
@RequestMapping("/findAllStudent")
public Result test1(){
Result result = new Result();
List<Student> student = studentService.findAllStudent();
result.setData(student);
return result;
}
@RequestMapping("findSomeColumn")
public Result test2(){
Result result = new Result();
List<Student> stu = studentService.findSomeColumn();
result.setData(stu);
return result;
}
@RequestMapping("deleteById/{id}")
public Result test3(@PathVariable Integer id){
Result result = new Result();
studentService.deleteById(id);
result.setMsg("删除成功");
return result;
}
@RequestMapping("updateByPrimarKeySelective")
public Result test4(@RequestBody Student student){
Result result = new Result();
EntityWrapper<Student> entityWrapper = new EntityWrapper<>();
entityWrapper.eq("stu_mobile", student.getStuMobile());
Student stu = studentService.selectOne(entityWrapper);
if (null != stu) {
stu.setParName("my hero");
stu.setStuName("zxs");
}
studentService.updateByPrimarKeySelective(stu);
result.setData(stu);
return result;
}
@RequestMapping("/saveStudent")
public Result<Student> test5(@RequestBody Student student){
Result<Student> result = new Result<Student>();
studentService.saveStudent(student);
result.setData(student);
return result;
}
/**
* 分页的方法
* @param pageNumber
* @param pageSize
* @return
*/
@RequestMapping("page/{pageNumber}")
public Result findAllStuPage(@PathVariable Integer pageNumber,
@RequestParam(defaultValue="6") Integer pageSize){
Result result = new Result();
Page page = new Page(pageNumber,pageSize);
Page<Student> pageStu = studentService.findAllStudentPage(page);
result.setData(pageStu.getRecords());
return result;
}
@RequestMapping("pageByGender/{pageNumber}")
public Result findStuByGender(@PathVariable Integer pageNumber,
@RequestParam(defaultValue="6") Integer pageSize){
Result result = new Result<>();
EntityWrapper<Student> wrapper = new EntityWrapper<>();
wrapper.eq("gender", 1);
Page<Student> page = getPage(pageNumber, pageSize);
Page<Student> stuPage = studentService.selectPage(page, wrapper);
result.setData(stuPage.getRecords());
return result;
}
/**
* 获取分页对象
* 每页显示数量
*/
private <T> Page<T> getPage(int pageNum,int pageSize){
return new Page<T>(pageNum,pageSize);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
SpringBoot的启动类:
package com.cn.restyle;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.cn.restyle.mapper") //配置mapper扫描
@SpringBootApplication
public class CrmApplication {
public static void main(String[] args) {
SpringApplication.run(CrmApplication.class, args);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
另外,对于EntityWrapper的条件拼接,基本可以实现SQL中常用的where,and,or,groupby, orderby等语法
@Test
public void testSql(String str){
EntityWrapper<Student> wrapper = new EntityWrapper<>();
wrapper.eq("stu_name", str)
.or()
.eq("par_name", str)
.orderBy("create_time", false) // 时间的倒叙排列
.limit(0, 1); // 取一条
Student stu = studentService.selectOne(wrapper);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
附:
我的Result 工具类
package com.cn.restyle.util;
public class Result<T> {
public static final Integer OK = 0;
public static final Integer Error = -1;
private Integer code;
private String msg;
private T data;
public Result(){
this.code = OK;
this.msg = "success";
}
public Result(Integer code, String msg) {
super();
this.code = code;
this.msg = msg;
}
public Result(String msg, T data) {
super();
this.msg = msg;
this.data = data;
}
public Result(Integer code, String msg, T data) {
super();
this.code = code;
this.msg = msg;
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
参考文档:
上一篇: springboot 多数据源
下一篇: mysql多数据源