MyBatis-Plus ActiveRecord模式
ActiveRecord模式
Mybatis-Plus中提供了ActiveRecord模式,支持ActiveRecord形式调用,实体类只需继承Model类即可实现基本CRUD操作,简单来说就是一个实体类继承Model类,并通过注解与数据库的表名进行关联。这样就可以通过实体类直接进行表的简单增删改查操作。
和BaseMapper其实是类似的
package com.example.wx_test.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;
@TableName("t_department")
@Data
@EqualsAndHashCode(callSuper = false)
public class Department extends Model<Department> {
@TableId(type = IdType.AUTO)
private Integer id; // 编号
private String name; // 名称
private String remark; // 备注
}
insert
@Test
public void insert(){
Department department = new Department();
department.setName("神秘部门");
department.setRemark("神秘部门测试");
boolean result = department.insert();
System.out.println(result);
}
运行结果
updatebyId
@Test
public void updatebyId(){
Department department = new Department();
department.setId(14);
department.setName("摸鱼部门");
department.setRemark("摸鱼部门测试");
boolean result = department.updateById();
System.out.println(result);
}
运行结果
insertOrUpdate
@Test
public void insertOrUpdate1(){
Department department = new Department();
department.setId(15);
department.setName("划水部门");
department.setRemark("划水部门测试");
boolean result = department.insertOrUpdate();
System.out.println(result);
}
数据库中已存在id为15的数据,进行更新,结果如下:
@Test
public void insertOrUpdate2(){
Department department = new Department();
department.setId(16);
department.setName("划水部门1");
department.setRemark("划水部门测试1");
boolean result = department.insertOrUpdate();
System.out.println(result);
}
数据库中不存在id为16的数据,执行insert操作
deleteById
@Test
public void deletebyId1(){
Department department = new Department();
department.setId(16);
department.deleteById();
department.deleteById(15);
}
运行结果
selectById
@Test
public void selectById(){
Department department = new Department();
department.setId(1);
department.selectById();
department.selectById(2);
}
运行结果
selectAll
@Test
public void selectAll(){
Department department = new Department();
department.selectAll();
}
selectByQueryWrapper
@Test
public void selectByQueryWrapper(){
Department department = new Department();
QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name","部");
List<Department> departmentList = department.selectList(queryWrapper);
System.out.println(departmentList);
}
参考资料
- https://www.bilibili.com/video/BV1KV411U7pH?p=19
- https://blog.csdn.net/qq924862077/article/details/81836309?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165120436016781483766564%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=165120436016781483766564&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_ecpm_v1~rank_v31_ecpm-1-81836309.142v9pc_search_result_cache,157v4control&utm_term=activerecord&spm=1018.2226.3001.4187
|