mybatis-plus官网:https://mybatis.plus
springboot 2.1.7
maven 3.5.0
mysql 5.7.24
mybatis-plus 3.2.0
一、新建SpringBoot项目
在mybatis-plus官网上看到:
引入 MyBatis-Plus 之后请不要再次引入 MyBatis 以及 MyBatis-Spring,以避免因版本差异导致的问题。
因此我选择了新建项目整合尝试。
1.pom文件maven依赖如下所示:
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
com.baomidou
mybatis-plus-boot-starter
3.2.0
com.baomidou
mybatis-plus
3.2.0
2.application.yml配置文件如下所示:
#自定义项目端口号
server:
port: 6000
session-timeout: 30
tomcat.max-threads: 0
tomcat.uri-encoding: UTF-8
#mysql
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo
username: root
password: 123456
3.启动类配置 MapperScan 注解
package com.liulin.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.liulin.demo.mapper")
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
4.项目结构
在使用maven等构建工具时,默认会将源码(java文件夹)编译后再加上资源目录(resources文件夹)的文件放到target目录下作为最后运行的文件,xml文件放到Java文件夹里,编译时会被maven忽略,因此常采用在resources下新建文件夹,用来存放mapper的xml文件。
二、代码准备
1.表结构
这里我使用了MP官网给的表。
CREATE TABLE user (
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
其对应的数据库Data脚本:
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]'),
(6, 'JackSon', 27, '[email protected]');
2.实体类
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
3.DAO层
Mapper通用CRUD封装BaseMapper接口,自动解析实体表关系映射转换为 Mybatis 内部对象注入容器
package com.liulin.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.liulin.demo.entity.User;
/**
* Created by liulin on 2019-08-29 23:44
*/
public interface UserMapper extends BaseMapper {
}
4.Service层
通用Service CRUD封装IService接口
get 查询单行
remove 删除
list 查询集合
page 分页
(1) Service类
package com.liulin.demo.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.liulin.demo.entity.User;
/**
* Created by liulin on 2019-09-02 23:48
*/
public interface UserService extends IService {
}
(2) ServiceImpl类
package com.liulin.demo.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liulin.demo.entity.User;
import com.liulin.demo.mapper.UserMapper;
import com.liulin.demo.service.UserService;
import org.springframework.stereotype.Service;
/**
* Created by liulin on 2019-09-02 23:57
*/
@Service
public class UserServiceImpl extends ServiceImpl implements UserService {
}
5.Controller层
package com.liulin.demo.controller;
import com.liulin.demo.entity.User;
import com.liulin.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by liulin on 2019-09-03 14:43
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired UserService userService;
@PostMapping("/getUserInfo")
public User getUserInfo(Integer userId) {
User user = userService.getById(userId);
return user;
}
}
三、Postman调试
1.以getUserInfo方法为例
Postman(localhost:6000/user/getUserInfo?userId=1)输出结果如下:
{
"id":1,
"name":"Jone",
"age":18,
"email":"[email protected]"
}
可以看到,Service、Mapper一个方法都没写的情况下,从表里查出了userId为1的全部信息,省去了mybatis中xml的sql查询那一步,在官方给出的文档中,可以看到基本上都是基于主键id返回单一实体或实体list。
2.条件构造器
(1)查询年龄等于28的结果
因为表是自建,age=18的结果只有1条,所以这里使用的是IService的getOne方法,如果是多条结果的话,该方法就会报错。
@PostMapping("/getUserByAge")
public User getUserByAge(int age) {
QueryWrapper queryWrapper = new QueryWrapper<>();
//lambda写法:
queryWrapper.lambda().eq(User::getAge, age);
User user = userService.getOne(queryWrapper);
return user;
}
Postman(localhost:6000/user/getUserByAge?age=18)输出结果如下:
{
"id": 3,
"name": "Tom",
"age": 28,
"email": "[email protected]"
}
(2)查询年龄大于20小于25的结果
@PostMapping("/getUserListByAgeLimit")
public List getUserListByAgeLimit() {
QueryWrapper queryWrapper = new QueryWrapper<>();
queryWrapper.lambda().gt(User::getAge, 20);
queryWrapper.lambda().lt(User::getAge, 25);
List userList = userService.list(queryWrapper);
return userList;
}
Postman(localhost:6000/user/getUserListByAgeLimit)输出结果如下:
[
{
"id": 4,
"name": "Sandy",
"age": 21,
"email": "[email protected]"
},
{
"id": 5,
"name": "Billie",
"age": 24,
"email": "[email protected]"
}
]
(3)自定义sql
使用Wrapper构造条件自定义sql子句,官网提供了两种方案:
第一种:Mapper.java使用注解
package com.liulin.demo.mapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.liulin.demo.entity.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* Created by liulin on 2019-08-29 23:44
*/
public interface UserMapper extends BaseMapper {
@Select("select * from user ${ew.customSqlSegment} ")
List getUserListByCondition(@Param(Constants.WRAPPER) QueryWrapper condition);
}
Service层
package com.liulin.demo.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.liulin.demo.entity.User;
import java.util.List;
/**
* Created by liulin on 2019-09-02 23:48
*/
public interface UserService extends IService {
List getUserListByCondition(String name);
}
ServiceImpl类
package com.liulin.demo.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liulin.demo.entity.User;
import com.liulin.demo.mapper.UserMapper;
import com.liulin.demo.service.UserService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by liulin on 2019-09-02 23:57
*/
@Service
public class UserServiceImpl extends ServiceImpl implements UserService {
@Override
public List getUserListByCondition(String name) {
QueryWrapper condition = new QueryWrapper<>();
//like模糊查询且年龄小于25
condition.lambda().like(User::getName, name).lt(User::getAge, 25);
return baseMapper.getUserListByCondition(condition);
}
}
Controller层
@PostMapping("/getUserListBySql")
public List getUserListBySql(String name) {
List userList = userService.getUserListByCondition(name);
return userList;
}
Postman(localhost:6000/user/getUserListBySql?name=Jac)输出结果如下:
[
{
"id": 2,
"name": "Jack",
"age": 20,
"email": "[email protected]"
}
]
第二种:Mapper.xml文件
四、其他
1.mybatis-plus配置执行sql输出到控制台
application.yml文件:
mybatis-plus:
configuration:
#控制台打印完整带参数SQL语句
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
有SQL执行时,控制台输出结果如下:
JDBC Connection [HikariProxyConnection@1882318550 wrapping com.mysql.cj.jdbc.ConnectionImpl@2022fa88] will not be managed by Spring
==> Preparing: SELECT id,name,email,age FROM user WHERE (age = ?)
==> Parameters: 28(Integer)
<== Columns: id, name, email, age
<== Row: 3, Tom, [email protected], 28
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3291f605]
2.使用Mapper.xml形式时配置文件
application.yml文件
mybatis-plus:
configuration:
#控制台打印完整带参数SQL语句
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#resources目录下
mapper-locations: classpath:/mapper/**.xml
总结:
1、mybatis-plus是mybatis的增强版,在MyBatis的基础上只做增强不做改变。
2、mybatis-plus官网条件构造器一节中提供了eq、ne、like、isNull、having等拼接的方法,使用lambda写法使之简洁有效,单表操作的情况下,使用Mapper和Service封装的CURD方法节约代码量和工作量。
3、在多表联合复杂查询的时候就需要在xml文件里写sql语句。
以上就是SpringBoot整合mybatis-plus整合学习过程,关于mybatis-plus方法,只学习了select的用法,其他增改删后期还需结合官网加以实践,熟练操作。