前言
这部分(AR、逻辑删除、MP通过version实现的乐观锁、自动填充)功能写项目的时候用来着,就是学的急就没有写笔记。
这个是自己学习时候记得笔记要是想详细了解可以去MP官网,上边有更详细的配置流程以及视频教学:MyBatis-Plus
什么是AR模式(Active Record)
通过实体类对象直接进行对表的增删改查操作(JPA)
准备工作
- 实体类extends Model< T >
- 对应实体类有对应操作的Mapper接口,接口继承BaseMapper< T >
代码
- Service层此时不用注入对应的Mapper接口
- 插入:直接调用对象上的insert()方法,返回值为是否插入成功
public void insertArType(){
Type type = new Type();
type.setName("类型");
type.setParentId(1);
boolean inserted = type.insert();
System.out.println("AR插入"+inserted);
}
- 查询,直接用实体类上的select…方法
注意:调用select…方法的对象,与实际返回的对象并不是指向同一个对象
public Type selectById(){
Type type = new Type();
Type type1 = type;
type1.setName("aa");
System.out.println(type1 == type); // true
Type type2 = type.selectById(2);
System.out.println(type2 == type); // false
return type2;
}
public Type selectById2(){ // 通过在原对象中设置id,进行查询
Type type = new Type();
type.setTypeId(2);
Type type1 = type.selectById();
System.out.println(type == type1); // false,返回仍为新对象
return type1;
}
查询操作也提供了 selectAll() 用List返回所有对象;通过设置QueryWrapper< T > 的selectList()、selectOne()、selectCount();以及分页的selectPage() api
对于selectOne(),在非AR模式下,多于一条查询结果会报错。而现在大于1条时取第一条,并打印警告。
- 更新操作
可通过updateById(),在调用这个方法的实体对象中设置id;
也可以通过使用updateWrapper进行条件构造
public void updateType(){
Type type = new Type();
type.setTypeId(2);
type.setName("bbb");
boolean updated = type.updateById(); // 返回值为是否更新成功
System.out.println(updated);
}
- 删除操作
通过调用deleteById(),在调用这个方法的实体对象中设置id参数
通过调用deleteById(int id),可不用设置id参数
通过调用delete(QueryWrapper),通过构造querywrapper条件来执行删除
返回值依旧为是否删除成功
public void deleteType(){
Type type = new Type();
type.setTypeId(2);
boolean deleted = type.deleteById();
System.out.println(deleted);
}
- insertOrUpdate()
如果在实体类中没有设置id,那么执行insert();
如果在实体类中设置了id,先查询有没有对应记录,如果有执行update();如果没有则执行insert();
public void insOrUpd(){
Type type = new Type();
type.setTypeId(2);
type.setName("bbb");
boolean inOrUped = type.insertOrUpdate();
}