DELETE
FROM children;
DELETE FROM user;
INSERT INTO children (id, name, user_id)
VALUES (1, 'Jone', 1),
(2, 'Jack', 1),
(3, 'Jack2', 1),
(4, 'Jack', 15),
(5, 'Billie', 15);
INSERT INTO user (id, name, age, email)
VALUES (1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Jack', 20, '[email protected]'),
(4, 'Jack', 20, '[email protected]'),
(5, 'Jack', 20, '[email protected]'),
(6, 'Jack', 20, '[email protected]'),
(7, 'Jack', 20, '[email protected]'),
(8, 'Jack', 20, '[email protected]'),
(9, 'Jack', 20, '[email protected]'),
(10, 'Jack', 20, '[email protected]'),
(11, 'Jack', 20, '[email protected]'),
(12, 'Jack', 20, '[email protected]'),
(13, 'Jack', 20, '[email protected]'),
(14, 'Jack', 20, '[email protected]'),
(15, 'Tom', 28, '[email protected]'),
(16, 'Sandy', 21, '[email protected]'),
(17, 'Billie', 24, '[email protected]');
-- noinspection SqlNoDataSourceInspectionForFile
DROP TABLE IF EXISTS user;
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)
);
DROP TABLE IF EXISTS children;
CREATE TABLE children
(
id BIGINT (20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
user_id BIGINT (20) NULL DEFAULT NULL COMMENT '上级ID',
PRIMARY KEY (id)
);
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zs</groupId>
<artifactId>test-mybatis-plus</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>test-mybatis-plus</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.4.3.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.zs.testmybatisplus.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
/**
* @author miemie
* @since 2018-08-10
*/
@Configuration
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
// @Bean
// public ConfigurationCustomizer configurationCustomizer() {
// return configuration -> configuration.setUseDeprecatedExecutor(false);
// }
}
# Logger Config
logging:
level:
com.baomidou.mybatisplus.samples: debug
mybatis-plus:
mapper-locations: classpath:/mapper/*Mapper.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test_zs?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
username: root
password: root
package com.zs.testmybatisplus.mapper;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.session.RowBounds;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zs.testmybatisplus.entity.User;
import com.zs.testmybatisplus.model.MyPage;
import com.zs.testmybatisplus.model.ParamSome;
import com.zs.testmybatisplus.model.UserChildren;
/**
* @author miemie
* @since 2018-08-10
*/
@Mapper
public interface UserMapper extends BaseMapper<User> {
/**
* 3.x 的 page 可以进行取值,多个入参记得加上注解
* 自定义 page 类必须放在入参第一位
* 返回值可以用 IPage 接收 也可以使用入参的 MyPage 接收
* 3.1.0 之前的版本使用注解会报错,写在 xml 里就没事
* 3.1.0 开始支持注解,但是返回值只支持 IPage ,不支持 IPage 的子类
*
* @param myPage 自定义 page
* @return 分页数据
*/
// @Select("select * from user where (age = #{pg.selectInt} and name = #{pg.selectStr}) or (age = #{ps.yihao} and name = #{ps.erhao})")
MyPage<User> mySelectPage(@Param("pg") MyPage<User> myPage, @Param("ps") ParamSome paramSome);
@SuppressWarnings("checkstyle:OperatorWrap")
@ResultMap("userChildrenMap")
@Select("")
MyPage<UserChildren> userChildrenPage(MyPage<UserChildren> myPage);
MyPage<User> mySelectPageMap(MyPage<User> pg, Map<String, Object> map);
List<User> mySelectMap(Map<String, Object> param);
List<User> myPageSelect(MyPage<User> myPage);
List<User> iPageSelect(IPage<User> myPage);
List<User> rowBoundList(RowBounds rowBounds, Map<String, Object> map);
}
<?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.zs.testmybatisplus.mapper.UserMapper">
<resultMap id="userChildrenMap" type="com.zs.testmybatisplus.model.UserChildren">
<id column="id" property="id"/>
<result column="age" property="age"/>
<result column="email" property="email"/>
<result column="name" property="name"/>
<collection property="c" ofType="com.zs.testmybatisplus.entity.Children" columnPrefix="c_">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="user_id" property="userId"/>
</collection>
</resultMap>
<select id="mySelectPage" resultType="com.zs.testmybatisplus.entity.User">
select *
from user
where (age = #{pg.selectInt} and name = #{pg.selectStr})
or (age = #{ps.yihao} and name = #{ps.erhao})
</select>
<select id="mySelectPageMap" resultType="com.zs.testmybatisplus.entity.User">
select * from user
<where>
<if test="map.name!=null and map.name!=''">
name like #{map.name}
</if>
</where>
</select>
<select id="mySelectMap" resultType="com.zs.testmybatisplus.entity.User">
select * from user
<where>
<if test="name!=null and name!=''">
name like #{name}
</if>
</where>
</select>
<select id="myPageSelect" resultType="com.zs.testmybatisplus.entity.User">
select * from user
<where>
<if test="name!=null and name!=''">
name like '%'||#{name}||'%'
</if>
</where>
</select>
<select id="iPageSelect" resultType="com.zs.testmybatisplus.entity.User">
select * from user
<where>
<if test="name!=null and name!=''">
name like #{name}
</if>
</where>
</select>
<select id="rowBoundList" resultType="com.zs.testmybatisplus.entity.User">
select * from user
<where>
<if test="name!=null and name!=''">
name like #{name}
</if>
</where>
</select>
</mapper>
package com.zs.testmybatisplus.model;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* @author miemie
* @since 2018-08-10
*/
@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
public class MyPage<T> extends Page<T> {
private static final long serialVersionUID = 5194933845448697148L;
private Integer selectInt;
private String selectStr;
private String name;
public MyPage(long current, long size) {
super(current, size);
}
}
package com.zs.testmybatisplus.model;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* @author miemie
* @since 2018-08-10
*/
@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
public class MyPage<T> extends Page<T> {
private static final long serialVersionUID = 5194933845448697148L;
private Integer selectInt;
private String selectStr;
private String name;
public MyPage(long current, long size) {
super(current, size);
}
}
package com.zs.testmybatisplus.model;
import java.util.List;
import com.zs.testmybatisplus.entity.Children;
import com.zs.testmybatisplus.entity.User;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* @author miemie
* @since 2019-06-12
*/
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class UserChildren extends User {
private List<Children> c;
}
package com.zs.testmybatisplus.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.zs.testmybatisplus.entity.User;
/**
*
*
*
* @author yuxiaobin
* @date 2020/7/2
*/
public interface IUserService extends IService<User> {
}
package com.zs.testmybatisplus.service;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zs.testmybatisplus.entity.User;
import com.zs.testmybatisplus.mapper.UserMapper;
/**
*
*
*
* @author yuxiaobin
* @date 2020/7/2
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
}
package com.zs.testmybatisplus;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import javax.annotation.Resource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.ibatis.session.RowBounds;
import org.assertj.core.util.Maps;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zs.testmybatisplus.entity.User;
import com.zs.testmybatisplus.mapper.UserMapper;
import com.zs.testmybatisplus.model.MyPage;
import com.zs.testmybatisplus.model.ParamSome;
import com.zs.testmybatisplus.model.UserChildren;
import com.zs.testmybatisplus.service.IUserService;
import lombok.extern.slf4j.Slf4j;
@SpringBootTest
@Slf4j
class TestMybatisPlusApplicationTests {
@Resource
private UserMapper mapper;
@Test
void lambdaPagination() {
Page<User> page = new Page<>(1, 3);
Page<User> result = mapper.selectPage(page,
Wrappers.<User>lambdaQuery()
.ge(User::getAge, 1)
.orderByAsc(User::getAge));
System.out.println(result.getRecords());
assertThat(result.getTotal()).isGreaterThan(3);
assertThat(result.getRecords().size()).isEqualTo(3);
}
@Test
void tests1() {
log.error("----------------------------------baseMapper 自带分页-------------------------------------------------------");
Page<User> page = new Page<>(1, 5);
page.addOrder(OrderItem.asc("age"));
Page<User> userIPage = mapper.selectPage(page, Wrappers.<User>lambdaQuery()
.eq(User::getAge, 20)
.like(User::getName, "Jack"));
// assertThat(page).isSameAs(userIPage);
log.error("总条数 -------------> {}", userIPage.getTotal());
log.error("当前页数 -------------> {}", userIPage.getCurrent());
log.error("当前每页显示数 -------------> {}", userIPage.getSize());
List<User> records = userIPage.getRecords();
assertThat(records).isNotEmpty();
log.error("----------------------------------json 正反序列化-------------------------------------------------------");
String json = JSON.toJSONString(page);
log.info("json ----------> {}", json);
Page<User> page1 = JSON.parseObject(json, new TypeReference<Page<User>>() {});
List<User> records1 = page1.getRecords();
assertThat(records1).isNotEmpty();
assertThat(records1.get(0).getClass()).isEqualTo(User.class);
log.error("----------------------------------自定义 XML 分页-------------------------------------------------------");
MyPage<User> myPage = new MyPage<User>(1, 5).setSelectInt(20).setSelectStr("Jack");
ParamSome paramSome = new ParamSome(20, "Jack");
MyPage<User> userMyPage = mapper.mySelectPage(myPage, paramSome);
assertThat(myPage).isSameAs(userMyPage);
log.error("总条数 -------------> {}", userMyPage.getTotal());
log.error("当前页数 -------------> {}", userMyPage.getCurrent());
log.error("当前每页显示数 -------------> {}", userMyPage.getSize());
}
@Test
void tests2() {
/* 下面的 left join 不会对 count 进行优化,因为 where 条件里有 join 的表的条件 */
MyPage<UserChildren> myPage = new MyPage<>(1, 5);
myPage.setSelectInt(18).setSelectStr("Jack");
MyPage<UserChildren> userChildrenMyPage = mapper.userChildrenPage(myPage);
List<UserChildren> records = userChildrenMyPage.getRecords();
records.forEach(System.out::println);
/* 下面的 left join 会对 count 进行优化,因为 where 条件里没有 join 的表的条件 */
myPage = new MyPage<UserChildren>(1, 5).setSelectInt(18);
userChildrenMyPage = mapper.userChildrenPage(myPage);
records = userChildrenMyPage.getRecords();
records.forEach(System.out::println);
}
private <T> void print(List<T> list) {
if (!CollectionUtils.isEmpty(list)) {
list.forEach(System.out::println);
}
}
@Test
void testMyPageMap() {
MyPage<User> myPage = new MyPage<User>(1, 5).setSelectInt(20).setSelectStr("Jack");
mapper.mySelectPageMap(myPage, Maps.newHashMap("name", "%k"));
myPage.getRecords().forEach(System.out::println);
}
@Test
void testMap() {
mapper.mySelectMap(Maps.newHashMap("name", "%a")).forEach(System.out::println);
}
@Test
void myPage() {
MyPage<User> page = new MyPage<>(1, 5);
page.setName("a");
mapper.myPageSelect(page).forEach(System.out::println);
}
@Test
void iPageTest() {
IPage<User> page = new Page<User>(1, 5) {
private String name = "%";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
};
List<User> list = mapper.iPageSelect(page);
System.out.println("list.size=" + list.size());
System.out.println("page.total=" + page.getTotal());
}
/**
* 只查询当前页的记录,不查询总记录数
*/
@Test
void currentPageListTest() {
//使用三参数的构造器创建Page对象
//第三个参数isSearchCount:传true则查询总记录数;传false则不查询总记录数(既不进行count查询)
Page<User> page = new Page<>(1,3,false);
Page<User> result = mapper.selectPage(page, Wrappers.<User>lambdaQuery()
.ge(User::getAge, 20));
assertThat(result.getRecords().size()).isEqualTo(3);
//因为没有进行count查询,total值为0
assertThat(result.getTotal()).isEqualTo(0);
}
@Test
void rowBoundsTest() {
RowBounds rowBounds = new RowBounds(0, 5);
List<User> list = mapper.rowBoundList(rowBounds, Maps.newHashMap("name", "%"));
System.out.println("list.size=" + list.size());
}
@Test
void selectAndGroupBy() {
LambdaQueryWrapper<User> lq = new LambdaQueryWrapper<>();
lq.select(User::getAge).groupBy(User::getAge);
for (User user : mapper.selectList(lq)) {
System.out.println(user.getAge());
}
}
@Autowired
IUserService userService;
@Test
void lambdaPageTest() {
LambdaQueryChainWrapper<User> wrapper2 = userService.lambdaQuery();
wrapper2.like(User::getName, "a");
userService.page(new Page<>(1, 10), wrapper2.getWrapper()).getRecords().forEach(System.out::print);
}
@Test
void test() {
userService.lambdaQuery().like(User::getName, "a").list().forEach(System.out::println);
Page page = userService.lambdaQuery().like(User::getName, "a").page(new Page<>(1, 10));
page.getRecords().forEach(System.out::println);
}
}
IPage<ProjectBaseDTO> projectBaseDTOIPage = projectMapper
.searchProjectInfoByLeaderMine(new Page<ProjectBaseDTO>(pageNumber, pageSize),
RoleEnum.LEADER.getCode(), projectStage, projectName,
projectNumber, projectCode, promoter,
projectType, projectProcess, participant,
currentLoginPersonId);
IPage<ProjectBaseDTO> searchProjectInfoByLeaderMine(@Param("page") Page<ProjectBaseDTO> page, @Param("roleEnum") Integer roleEnum, @Param("projectStage") Integer projectStage, @Param("projectName") String projectName, @Param("projectNumber") String projectNumber, @Param("projectCode") String projectCode, @Param("promoter") String promoter,
@Param("projectType") Integer projectType, @Param("projectProcess") Integer projectProcess, @Param("participant") Integer participant, @Param("currentLoginPersonId") String currentLoginPersonId);