mybatis-plus整合springboot入门
1、mybatis-plus快速入门
2、springboot整合mybatis-plus
(1)、映入maven依赖
<!--mybaitsi-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>
备注:springboot版本:2.2.6.RELEASE
(2)、yml文件数据库和mybatis-plus配置
#数据库配置
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybaits-plus?useUnicode=true&characterEncoding=UTF-8&useSSL=false&nullCatalogMeansCurrent=true&serverTimezone=Asia/Shanghai
#mybatis-plus配置
logging:
level:
com:
example:
demo:
mapper: debug
mybatis-plus:
mapper-locations: classpath*:mappers/*.xml
# 实体扫描,多个package用逗号或者分号分隔
type-aliases-package: com.example.demo.model
configuration:
# 驼峰下划线转换
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
global-config:
# 刷新mapper 调试神器
refresh: true
banner: false
#数据库大写下划线转换
#capital-mode: true
#序列接口实现类配置
#key-generator: com.baomidou.springboot.xxx
# 数据库相关配置
db-config:
db-type: mysql
# 主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID",ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
id-type: AUTO
# 字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断"
field-strategy: not_empty
capital-mode: true
#逻辑删除配置
logic-delete-value: 1
logic-not-delete-value: 0
(3)、数据准备
CREATE TABLE `user` (
`id` bigint(11) NOT NULL COMMENT '主键ID',
`name` varchar(30) NOT NULL COMMENT '姓名',
`age` int(11) NOT NULL COMMENT '年龄',
`email` varchar(50) NOT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES ('1', 'Jone', '18', 'test1@baomidou.com');
INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES ('2', 'Jack', '20', 'test2@baomidou.com');
INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES ('3', 'Tom', '28', 'test3@baomidou.com');
INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES ('4', 'Sandy', '21', 'test4@baomidou.com');
INSERT INTO `mybaits-plus`.`user` (`id`, `name`, `age`, `email`) VALUES ('5', 'Billie', '24', 'test5@baomidou.com');
CREATE TABLE `course` (
`id` bigint(20) NOT NULL,
`course` varchar(10) NOT NULL,
`user_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `mybaits-plus`.`course` (`id`, `course`, `user_id`) VALUES ('1', '语文', '2');
(4)、创建实体类
@Data
public class User implements Serializable {
private static final long serialVersionUID = -5817579076869802231L;
private Long id;
private String name;
private Integer age;
private String email;
}
(5)、service层和dao层
public interface UserService extends IService<User> {
PageInfo<User> selectPage(int pageNo, int pageSize, User user);
PageInfo<User> selectPageCustom(int pageNo, int pageSize, User user);
PageInfo<Map<String, Object>> selectPageCustomMap(int pageNo, int pageSize);
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
@Resource
private UserMapper userMapper;
@Override
public PageInfo<User> selectPage(int pageNo, int pageSize, User user) {
Page<User> page = new Page<>(pageNo,pageSize,false);
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name",user.getName());
wrapper.orderByAsc("id");
page = userMapper.selectPage(page, wrapper);
return new PageInfo<>(page);
}
@Override
public PageInfo<User> selectPageCustom(int pageNo, int pageSize, User user) {
Page<User> page = new Page<>(pageNo,pageSize);
userMapper.pageMyQuery(page,user.getName());
return new PageInfo<>(page);
}
@Override
public PageInfo<Map<String, Object>> selectPageCustomMap(int pageNo, int pageSize) {
Page<Map<String, Object>> page = new Page<>(pageNo,pageSize);
page = userMapper.pageMyMapQuery(page);
return new PageInfo<>(page);
}
public interface UserMapper extends BaseMapper<User> {
Page<User> pageMyQuery(Page<User> pageInfo, @Param("name") String name);
Page<Map<String,Object>> pageMyMapQuery(Page pageInfo);
}
mapper文件
<?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.example.demo.mapper.UserMapper"> <select id="pageMyQuery" parameterType="User" resultType="User"> select id,name,age from user where name = #{name} </select> <select id="pageMyMapQuery" resultType="map"> SELECT * FROM course c LEFT JOIN `user` u on c.id = u.id </select> </mapper>
(6)、单元测试
1 @SpringBootTest
2 @RunWith(SpringRunner.class)
3 public class MybatisPlusTest {
4
5 @Autowired
6 private UserService userService;
7 /**
8 * 全局id生成器
9 */
10 @Autowired
11 private DefaultIdentifierGenerator defaultIdentifierGenerator;
12
13 /**
14 * list查询
15 */
16 @Test
17 public void selectList(){
18 List<User> list = userService.list();
19 Assert.assertEquals(6, list.size());
20 list.forEach(System.out::println);
21 }
22
23 /**
24 *单条插入
25 */
26 @Test
27 public void inset(){
28 User user = new User();
29 user.setName("张三");
30 user.setAge(20);
31 user.setEmail("1165523762@qq.com");
32 user.setId(defaultIdentifierGenerator.nextId(user));
33 userService.save(user);
34 }
35
36 /**
37 * 批量插入
38 */
39 @Test
40 public void saveBatch(){
41 List<User> list = new ArrayList<>();
42 User user1 = new User();
43 user1.setName("王五");
44 user1.setAge(20);
45 user1.setEmail("1234567@qq.com");
46 user1.setId(defaultIdentifierGenerator.nextId(user1));
47 list.add(user1);
48
49 User user2 = new User();
50 user2.setName("李四");
51 user2.setAge(20);
52 user2.setEmail("7654321@qq.com");
53 user2.setId(defaultIdentifierGenerator.nextId(user1));
54 list.add(user2);
55
56 userService.saveBatch(list);
57
58 }
59
60 /**
61 * 按照id集合删除
62 */
63 @Test
64 public void delBatch(){
65 List<Long> ids = new ArrayList<>();
66 ids.add(1259742998092120066L);
67 ids.add(1259749231041806337L);
68 userService.removeByIds(ids);
69 }
70
71 /**
72 * 分页查询
73 */
74 @Test
75 public void queryPage(){
76 User user = new User();
77 user.setName("李四");
78 PageInfo<User> userPageInfo = userService.selectPage(1,3,user);
79 System.err.println(userPageInfo);
80 }
81
82 /**
83 * 自定义分页查询返回T
84 */
85 @Test
86 public void queryPageCustom(){
87 User user = new User();
88 user.setName("李四");
89 PageInfo<User> userPageInfo = userService.selectPageCustom(1,3,user);
90 System.err.println(userPageInfo);
91 }
92
93 /**
94 * 自定义分页查询返回map
95 */
96 @Test
97 public void queryPageCustomMap(){
98 PageInfo<Map<String,Object>> userPageInfo = userService.selectPageCustomMap(1,3);
99 System.err.println(userPageInfo);
100 }
补充:PageInfo源码(自定义分页实体类)
@Data
public class PageInfo<T> {
/**
* 当前页
*/
private Long pageNo;
/**
* 每页显示条数
*/
private Long PageSize;
/**
* 总条数
*/
private Long total;
/**
* 结果集
*/
private List<T> result;
public PageInfo(Page<T> page) {
this.pageNo = page.getCurrent();
this.PageSize = page.getSize();
this.total = page.getTotal();
this.result = page.getRecords();
}
}
mybatis-plus配置类
@Configuration
public class MybatisPlusConfig {
/**
* 全局id生成器
* @return
*/
@Bean
public DefaultIdentifierGenerator identifierGenerator(){
return new DefaultIdentifierGenerator();
}
/**
* 分页插件
* @return
*/
@Bean
public PaginationInterceptor paginationInterceptor(){
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
// 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
}