文章目录
一、ActiveRecord
ActiveRecord是什么:
- 每一个数据库表对应创建一个类,类的每一个对象实例对应于数据库表的一行记录;通常表的每个字段在类中都有相应的FIeld.
- ActiveRecord负责把自己持久化,在ActiveRecord中封装了对数据库的访问,通过对象自己实现CRUD,实现优雅的数据库操作。
- ActiveRecord也封装了部分业务逻辑,可以作为业务对象使用。
1.AR之insert
1)数据库表
2)实体类
package com.suyv.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;
public class Dept extends Model<Dept> {
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
private String name;
private String mobile;
private Integer manager;
public Dept() {
}
public Dept(String name, String mobile, Integer manager) {
this.name = name;
this.mobile = mobile;
this.manager = manager;
}
public Dept(Integer id, String name, String mobile, Integer manager) {
this.id = id;
this.name = name;
this.mobile = mobile;
this.manager = manager;
}
@Override
public String toString() {
return "Dept{" +
"id=" + id +
", name='" + name + '\'' +
", mobile='" + mobile + '\'' +
", manager=" + manager +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Integer getManager() {
return manager;
}
public void setManager(Integer manager) {
this.manager = manager;
}
}
注:必须继承Model,Model定义了表的CRUD方法,Dept属性名和列名是一样的。
3)mapper
package com.suyv.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.suyv.pojo.Dept;
/**
* @des DeptMapper是不需要使用的,MP需要使用DeptMapper获取数据库信息
*/
public interface DeptMapper extends BaseMapper<Dept> {
}
注:不使用mapper,也需要定义这个类,MP通过mapper获取到表的结构;不定义时,MP报错无法获取表的结构信息。
4)测试AR
@Test
public void testARInsert(){
Dept dept = new Dept();
dept.setName("销售部");
dept.setMobile("010-100865911");
dept.setManager(1);
boolean flag = dept.insert();
System.out.println("AR insert = " + flag);
}
2.AR之update
// 根据主键id修改
@Test
public void testARUpdate(){
Dept dept = new Dept();
dept.setId(1);
dept.setName("市场部");
dept.setMobile("010-22222222");
dept.setManager(2);
// UPDA