五、MyBatisPlus活动记录ActiveRecord
5.1 简介
Active Record是一种领域模型模式,特点是一个模型类对应关系型数据库中的一个表,而模型类的一个实例对应表中的一条记录。
AR模式提供了一种更加便捷的方式实现CRUD操作,其底层调用的是MyBatis对应的方法,类似于语法糖(计算机语言中添加的某种语法,这种语法对原本语言的功能并没有影响,可以更方便开发者使用,可以避免出错的机会,让程序可读性更好)。
5.2 使用
使用方法很简单,首先让我们的实体类继承Model(import com.baomidou.mybatisplus.extension.activerecord.Model;)。他的泛型是实体类本类。如下:
package com.example.boot.bean;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data //自动生成setter和getter
@ToString //自动生成toString方法
@AllArgsConstructor //自动生成全参构造
@NoArgsConstructor //自动生成无参构造
public class Student extends Model<Student> {
/**
* 主键,让数据库自增
*/
@TableId(type = IdType.AUTO)
private Integer id;
private String name;
private String email;
private Integer age;
}
然后,我们就可以直接跳过所谓的Mapper和Service啥的,直接对数据库进行增删改查了。
这里给出增删改查的代码:
增加操作:自己调用insert方法主动插入
package com.example.boot;
import com.example.boot.bean.Student;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class ARTest {
@Test
public void testInsert(){
Student student = new Student();
student.setName("李白");
student.setEmail("libai@qq.com");
student.setAge(23);
//自己插自己即可将自己这条数据作为一条记录插入数据库
student.insert();
}
}
结果:
修改操作:自己调用updateById方法主动修改(也可以使用update传入我们的条件选择器根据其他的属性或者条件进行修改。)
@Test
public void testUpdate(){
Student student = new Student();
student.setId(2029);
student.setEmail("libai@hstc.com");
student.updateById();
}
结果:
查询操作:自己调用selectById方法查询单条记录,如果该对象设置了id值,那么就直接调用selectById方法,如果该对象的id值为空,我们也可以直接在selectById方法中传入id的值。
@Test
public void testSelectById(){
Student student = new Student();
//方法一、直接使用selectById传入id值
Student object = student.selectById(2029);
//方法二、该对象设置id值后调用selectById方法
//student.setId(2029);
//student.selectById();
System.out.println(object);
}
结果:
如果是查询所有记录,也很简单(直接用实体类对象调用selectAll方法即可):
@Test
public void testSelectAll(){
Student student = new Student();
List<Student> studentList = student.selectAll();
for (Student item : studentList){
System.out.println(item);
}
}
结果:
select相关的还有以下方法:
- selectCount:查询有多少条记录,可以添加条件选择器进行有条件的筛选,也可以传入null,查询总的记录数。
- selectOne:有条件的查询单挑记录
- selectList:有条件的查询多条记录
- selectPage:有条件的查询多条记录并进行分页
删除操作:实体类对象调用delete的各种方法进行删除
解释一下上面截图的三个方法:
- 第一个表示有条件的删除,传入的是条件选择器。
- 第二个是 id属性不为空的对象调用后删除具有同样id值的记录。
- 第三个是任意实体类对象调用后传入一个id值,删除具有相同id值的记录。