mybatis-plus提供支持ActiveRecord模式
在Mybatis-Plus中提供了ActiveRecord的模式,支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可实现基本 CRUD 操作,简单来说就是一个实体类继承Model类,并通过注解与数据库的表名进行关联,这样就可以通过实体类直接进行表的简单增删改查操作,这样也确实极大的方便了开发人员。
原理理解:
简单来说Mybatis-plus是基于Mybatis的基础之上进行开发的,其基本操作还是一个Mapper操作中对应一条sql语句,通过参数和返回值来处理sql语句的执行结果。那样我们可以理解Mybatis-Plus的ActiveRecord其实就是Mybatis-Plus给我们提供一些简单的增删改查操作SQl语句的自动生成操作,在Mybatis提供的BaseMapper中默认提供了一些简单增删改查操作,其通过自动生成sql来初始化Mybatis的一些操作,其最终实现和我们直接基于Mybatis开发是一致的。
具体实现:
实体继承Model类,以及加上@EqualsAndHashCode(callSuper = false)注解,不调用父类euqals和hashCode方法;
@Data @EqualsAndHashCode(callSuper = false) public class Department extends Model<Department>
CRUD demo案例:
package com.java1234; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.java1234.entity.Department; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; /** * @author java1234_小锋 * @site www.java1234.com * @company Java知识分享网 * @create 2020-08-22 17:07 */ @RunWith(SpringRunner.class) @SpringBootTest public class ActiveRecordTest { @Test public void insert(){ Department department=new Department(); department.setName("xx部门"); department.setRemark("xxx"); boolean insert = department.insert(); System.out.println(insert); } @Test public void updateById(){ Department department=new Department(); department.setId(7); department.setName("xx部门2"); department.setRemark("xxx2"); boolean b = department.updateById(); System.out.println(b); } @Test public void insertOrUpdate(){ Department department=new Department(); department.setId(8); department.setName("xx部门2"); department.setRemark("xxx2"); boolean b = department.insertOrUpdate(); System.out.println(b); } @Test public void deleteById(){ Department department=new Department(); department.setId(7); boolean b = department.deleteById(); System.out.println(b); } @Test public void selectById(){ Department department=new Department(); //Department d = department.selectById(1); // 方式一 department.setId(1); // 方式二 Department d = department.selectById(); System.out.println(d); } @Test public void selectAll(){ Department department=new Department(); List<Department> departmentList = department.selectAll(); System.out.println(departmentList); } @Test public void selectListByQueryMapper(){ QueryWrapper<Department> queryWrapper=new QueryWrapper(); // QueryWrapper<Employee> queryWrapper2=Wrappers.<Employee>query(); queryWrapper.like("name","测试"); Department department=new Department(); List<Department> departmentList = department.selectList(queryWrapper); System.out.println(departmentList); } }