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)
);
DELETE FROM user;
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]');
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<exclusions>
<exclusion>
<groupId>org.junit.vintagegroupId>
<artifactId>junit-vintage-engineartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.0.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
dependencies>
#mysql数据库连接
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
@SpringBootApplication
@MapperScan("com.alex.mybatisplus.mapper")
public class MybatisPlusApplication {
......
}
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
@Repository
public interface UserMapper extends BaseMapper<User> {
}
- 添加测试类,进行功能测试:
@SpringBootTest
class MpdemoApplicationTests {
@Autowired
private UserMapper userMapper;
// 查询user表中的所有数据
@Test
public void findAll() {
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
/**
User(id=1, name=Jone, age=18, [email protected])
User(id=2, name=Jack, age=20, [email protected])
User(id=3, name=Tom, age=28, [email protected])
User(id=4, name=Sandy, age=21, [email protected])
User(id=5, name=Billie, age=24, [email protected])
*/
# mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
@RunWith(SpringRunner.class)
@SpringBootTest
public class CRUDTests {
@Autowired
private UserMapper userMapper;
@Test
public void testInsert(){
User user = new User();
user.setName("Helen");
user.setAge(18);
user.setEmail("[email protected]");
int result = userMapper.insert(user);
System.out.println(result); //影响的行数
System.out.println(user); //id自动回填
}
}
@TableId(type = IdType.AUTO)
private Long id;
#全局设置主键生成策略
mybatis-plus.global-config.db-config.id-type=auto
@Getter
public enum IdType {
/**
* 数据库ID自增
*/
AUTO(0),
/**
* 该类型为未设置主键类型
*/
NONE(1),
/**
* 用户输入ID
* 该类型可以通过自己注册自动填充插件进行填充
*/
INPUT(2),
/* 以下3种类型、只有当插入对象ID 为空,才自动填充。 */
/**
* 全局唯一ID (idWorker)
*/
ID_WORKER(3),
/**
* 全局唯一ID (UUID)
*/
UUID(4),
/**
* 字符串全局唯一ID (idWorker 的字符串表示)
*/
ID_WORKER_STR(5);
private int key;
IdType(int key) {
this.key = key;
}
}
@Test
public void updateUser() {
User user = new User();
user.setId(2L);
user.setAge(120);
int row = userMapper.updateById(user);
System.out.println(row);
}
项目中经常会遇到一些数据,每次都使用相同的方式填充,例如记录的创建时间,更新时间等。可以使用MyBatis Plus的自动填充功能,完成这些字段的赋值工作:
(1)数据库表中添加自动填充字段
在User表中添加datetime类型的新的字段 create_time、update_time
(2)实体上添加注解
@Data
public class User {
@TableField(fill = FieldFill.INSERT)
private Date createTime;
//@TableField(fill = FieldFill.UPDATE)
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
(3)实现元对象处理器接口
注意:不要忘记添加 @Component 注解
package com.atguigu.mybatisplus.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(MyMetaObjectHandler.class);
@Override
public void insertFill(MetaObject metaObject) {
LOGGER.info("start insert fill ....");
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("updateTime", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
LOGGER.info("start update fill ....");
this.setFieldValByName("updateTime", new Date(), metaObject);
}
}
(4)测试
(1)数据库中添加version字段
ALTER TABLE `user` ADD COLUMN `version` INT
(2)实体类添加version字段(并添加 @Version 注解)
@Version
@TableField(fill = FieldFill.INSERT)
private Integer version;
(3)元对象处理器接口添加version的insert默认值
@Override
public void insertFill(MetaObject metaObject) {
......
this.setFieldValByName("version", 1, metaObject);
}
/**
特别说明:
支持的数据类型只有 int,Integer,long,Long,Date,Timestamp,LocalDateTime
整数类型下 newVersion = oldVersion + 1
newVersion 会回写到 entity 中
仅支持 updateById(id) 与 update(entity, wrapper) 方法
在 update(entity, wrapper) 方法下, wrapper 不能复用!!!
*/
(4)在 MybatisPlusConfig 中注册 Bean
package com.atguigu.mybatisplus.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
@MapperScan("com.alex.mybatis_plus.mapper")
public class MybatisPlusConfig {
/**
* 乐观锁插件
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
(5)测试乐观锁可以修改成功
/**
* 测试 乐观锁插件成功
*/
@Test
public void testOptimisticLocker() {
//查询
User user = userMapper.selectById(1L);
//修改数据
user.setName("Helen Yao");
user.setEmail("[email protected]");
//执行更新
userMapper.updateById(user);
}
/**
* 测试乐观锁插件 失败
*/
@Test
public void testOptimisticLockerFail() {
//查询
User user = userMapper.selectById(1L);
//修改数据
user.setName("Helen Yao1");
user.setEmail("[email protected]");
//模拟取出数据后,数据库中version实际数据比取出的值大,即已被其它线程修改并更新了version
user.setVersion(user.getVersion() - 1);
//执行更新
userMapper.updateById(user);
}
MyBatis Plus自带分页插件,只要简单的配置即可实现分页功能
(1)创建配置类
此时可以删除主类中的 @MapperScan 扫描注解
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
(2)测试selectPage分页
测试:最终通过page对象获取相关数据
@Test
public void testSelectPage() {
Page<User> page = new Page<>(1,5);
userMapper.selectPage(page, null);
page.getRecords().forEach(System.out::println);
// 通过page对象获取分页数据
System.out.println(page.getCurrent()); // 当前页
System.out.println(page.getRecords()); // 每页数据list集合
System.out.println(page.getSize()); // 每页显示记录数
System.out.println(page.getTotal()); // 总记录数
System.out.println(page.getPages()); // 总页数
System.out.println(page.hasNext()); // 下一页
System.out.println(page.hasPrevious()); // 上一页
}
// 控制台sql语句打印:SELECT id,name,age,email,create_time,update_time FROM user LIMIT 0,5
(3)测试selectMapsPage分页:结果集是Map
@Test
public void testSelectMapsPage() {
Page<User> page = new Page<>(1, 5);
IPage<Map<String, Object>> mapIPage = userMapper.selectMapsPage(page, null);
//注意:此行必须使用 mapIPage 获取记录列表,否则会有数据类型转换错误
mapIPage.getRecords().forEach(System.out::println);
System.out.println(page.getCurrent());
System.out.println(page.getPages());
System.out.println(page.getSize());
System.out.println(page.getTotal());
System.out.println(page.hasNext());
System.out.println(page.hasPrevious());
}
@Test
public void testDeleteById(){
int result = userMapper.deleteById(8L);
System.out.println(result);
}
@Test
public void testDeleteBatchIds() {
int result = userMapper.deleteBatchIds(Arrays.asList(8, 9, 10));
System.out.println(result);
}
ALTER TABLE `user` ADD COLUMN `deleted` boolean
(2)实体类添加deleted 字段
@TableLogic
@TableField(fill = FieldFill.INSERT)
private Integer deleted;
(3)元对象处理器接口添加deleted的insert默认值
@Override
public void insertFill(MetaObject metaObject) {
......
this.setFieldValByName("deleted", 0, metaObject);
}
(4)application.properties 加入配置
此为默认值,如果你的默认值和mp默认的一样,该配置可无
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
(5)在 MybatisPlusConfig 中注册 Bean
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
(6)测试逻辑删除
测试后发现,数据并没有被删除,deleted字段的值由0变成了1
测试后分析打印的sql语句,是一条update
注意:被删除数据的deleted 字段的值必须是 0,才能被选取出来执行逻辑删除的操作
/**
* 测试 逻辑删除
*/
@Test
public void testLogicDelete() {
int result = userMapper.deleteById(1L);
System.out.println(result);
}
(7)测试逻辑删除后的查询
MyBatis Plus中查询操作也会自动添加逻辑删除字段的判断
/**
* 测试 逻辑删除后的查询:
* 不包括被逻辑删除的记录
*/
@Test
public void testLogicDeleteSelect() {
User user = new User();
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
/**
测试后分析打印的sql语句,包含 WHERE deleted=0
SELECT id,name,age,email,create_time,update_time,deleted FROM user WHERE deleted=0
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class QueryWrapperTests {
@Autowired
private UserMapper userMapper;
}
// mp实现复杂查询操作
@Test
public void testSelectQuery() {
// 创建对象
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 通过QueryWrapper设置条件
// ge、gt、le、lt
// 查询age >= 30的记录
// 第一个参数设置字段名称,第二个参数设置值
wrapper.ge("age", 30); // ☆
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
// eq、ne
// name等于/不等于lilei的数据
wrapper.eq("name","lilei"); // ☆
wrapper.ne("name", "lilei"); // ☆
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
// between 范围
// 查询年龄 20-30
wrapper.between("age", 20, 30); // ☆
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
// like 模糊查询
wrapper.like("name", "蔡"); // ☆
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
// orderByDesc 排序
wrapper.orderByDesc("id"); // ☆
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
// last 语句最后拼接sql语句
wrapper.last("limit 1"); // ☆
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
// select 指定要查询的列
wrapper.select("id","name"); // ☆
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}