升级版的mybatis,目的是让mybatis更易于使用, 用官方的话说“为简化而生”
官网:
Redirect
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]');
创建springboot工程需要指定parent
org.springframework.boot
spring-boot-starter-parent
2.6.1
依赖
org.springframework.boot
spring-boot-starter-data-jdbc
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
com.baomidou
mybatis-plus-boot-starter
3.4.3.4
spring.application.name=mpdemo
server.port=8080
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mp_db?useSSL=false&useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
@SpringBootApplication
@MapperScan("com.zking.mpdemo.**")
public class MpdemoApplication {
public static void main(String[] args) {
SpringApplication.run(MpdemoApplication.class, args);
}
}
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zking.mpdemo.model.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper extends BaseMapper
{
}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MpdemoApplication.class)
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testList() {
System.out.println(("----- selectAll method test ------"));
List
userList = userMapper.selectList(null); Assert.assertEquals(5, userList.size());
userList.forEach(System.out::println);
}
}
运行测试
application.properties
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
在开发中将sql语句打印到控制台,以便于调试
public enum IdType {
AUTO(0), //自动增长
NONE(1), //未(不)设置主键
INPUT(2), // 手动输入
ASSIGN_ID(3), // 雪花算法
ASSIGN_UUID(4); // 排除到下划线的UUID,32位长度
private final int key;
private IdType(int key) {
this.key = key;
}
public int getKey() {
return this.key;
}
}
@Test
public void testUpdate() {
User user = new User();
user.setId(6);
//ID用于定位sql,其他的列段设置几个就修改几个,没有设置的则保留原来的值
user.setName("Rose");
user.setAge(20);
int i = userMapper.updateById(user);
System.out.println(i);
}
在数据表的设计中,经常需要加一些字段,如:创建时间,最后修改时间等,此时可以使用mybatis-plus来帮我们进行自动维护
在自动填充有两种方式:
一: 通过数据库完成自动填充(数据库勾选)
@Data
public class User {
@TableId(type = IdType.AUTO)
private int id;
private String name;
private Integer age;
private String email;
//在代码中同步加入创建时间和最后修改时间的维护
private Date createTime;
private Date lastModifiedTime;
}
完成后可以通过新增或更新
二:使用程序完成自动填充
将数据库中的自动维护功能取消:
第一步:实体类中加入注解
//表明在插入时自动维护字段
@TableField(fill = FieldFill.INSERT)
private Date createTime;
//表明在插入和更新时自动维护字段
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date lastModifiedTime;
第二步:编写处理类
// 不要忘了处理器是spring的组件
@Component
public class AutoFillHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime",new Date(), metaObject);
this.setFieldValByName("lastModifiedTime",new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
//this.setFieldValByName("createTime",new Date(), metaObject);
this.setFieldValByName("lastModifiedTime",new Date(), metaObject);
}
}
完成后可以通过新增或更新
当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式(来自官方文档):
取出记录时,获取当前version
更新时,带上这个version
执行更新时, set version = newVersion where version = oldVersion
如果version不对,就更新失败
配置示例:
//乐观锁
@Version
private int version;
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
//测试乐观锁
@Test
public void testLock01() {
User user01 = userMapper.selectById(7L);
User user02 = userMapper.selectById(7L);
user01.setName("leguansuo01");
userMapper.updateById(user01);
user02.setName("leguansuo02");
userMapper.updateById(user02);
}
@Test
public void testSelectList() {
//一次查询多个ID
List
users = userMapper.selectBatchIds(Arrays.asList(1L, 2L, 3L)); users.forEach(t -> {
System.out.println(t);
});
}
@Test
public void testSelectByMap() {
//使用map进行查询
Map
map = new HashMap<>(); map.put("name", "Tom");
map.put("age", 28);
List
users = userMapper.selectByMap(map); users.forEach(t-> System.out.println(t));
}
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//乐观锁
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
//分页
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
@Test
public void testSelectPage() {
PageDTO
page = new PageDTO<>(); page.setCurrent(1);
page.setSize(5);
PageDTO
pageDTO = userMapper.selectPage(page, null);
System.out.println(pageDTO.getTotal());
List
records = pageDTO.getRecords(); records.forEach(t-> System.out.println(t));
}
注:dto是数据传输对象,通过这个对象给前端数据
物理删除使用起来比较简单,仿照查询功能即可,不再赘述。
什么是逻辑删除?
即:标记删除,并不是真的从数据库中删除,而是做个删除标记,在查询时,过滤掉标记为删除的记录即可。
//标记该字段为逻辑删除字段
@TableLogic
private int deleted;
#逻辑删除字段名
mybatis-plus.global-config.db-config.logic-delete-field=deleted
# 1表示逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
# 0 表示未删除
mybatis-plus.global-config.db-config.logic-not-delete-value=0
@Test
public void testDeleteLogic() {
int i = userMapper.deleteById(1L);
System.out.println(i);
}
用于构造查询条件
@Test
public void testWrapperLike() {
QueryWrapper
wrapper = new QueryWrapper<>(); wrapper.likeRight("name", "T")
.eq("age", 28);
List
users = userMapper.selectList(wrapper); users.forEach(t-> System.out.println(t));
}
@Test
public void testUpdateWrapper() {
UpdateWrapper u = new UpdateWrapper();
//u.set("name", "TT");
u.eq(true, "id", 6L);
User user = userMapper.selectById(6L);
//user = new User();
user.setName("TTT");
userMapper.update(user, u);
}
mybatis-plus是mybatis的升级版,所以在mybatis-plus中使用xml的配置比较简单
mybatis-plus.mapper-locations=classpath:/mapper/**/*.xml
@Repository
public interface UserMapperXml extends BaseMapper
{
List
list(); }
select * from user;
也可以不使用xml配置文件,使用注解来定义sql语句
public interface UserMapperXml extends BaseMapper
{
@Select("select * from user")
List
list();
}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MpdemoApplication.class)
public class UserMapperXmlTest {
@Autowired
private UserMapperXml userMapperXml;
//使用xml配置的方法
@Test
public void list() {
List
list = userMapperXml.list(); list.forEach(t-> System.out.println(t));
}
//mybatis-plus提供的方法
@Test
public void testSelectByID() {
User user = userMapperXml.selectById(2L);
System.out.println(user);
}
}