【Mybatis-Plus】04 AR (Active Record)

AR模式,全称激活记录

具体操作更接近Hibernate一样的OOP操作方式影响数据库记录

比Hibernate操作更灵活更方便

上手:

首先User实体类需要继承Model类并泛型注入User类型

如果使用了Lombok,需要再添加调用super的哈希值方法和比较方法(因为@Data注解)

package cn.echo42.pojo;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @author DaiZhiZhou
 * @file MP-Spring
 * @create 2020-08-05 22:36
 */


@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("sys_user")
@EqualsAndHashCode(callSuper = true)
public class User extends Model<User> implements Serializable {

    private static final long serialVersionUID = 8921929240003713006L;

    @TableId("user_id")
    private Integer userId; // private Integer user_id;

    private String userName; //  private String user_name; @TableField("user_name")

    private String userPassword; //  private String user_password; @TableField("user_password")

    private Integer userStatus; //  private Integer user_status; @TableField("user_status")

    private Integer userIsDel; //  private Integer user_is_del; @TableField("user_is_del")
}

执行操作时,我们可以使用实体对象完成SQL操作:

    @Test
    public void arQuery() {
        User user = new User();
        user.setUserId(2);

        User selectById = user.selectById();
        System.out.println(selectById);
    }

操作结果:

DEBUG [main] - Creating a new SqlSession
DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6c7a164b] was not registered for synchronization because synchronization is not active
DEBUG [main] - Fetching JDBC Connection from DataSource
DEBUG [main] - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/oa?serverTimezone=GMT]
DEBUG [main] - JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1a9c38eb] will not be managed by Spring
DEBUG [main] - ==>  Preparing: SELECT user_id,user_name,user_password,user_status,user_is_del FROM sys_user WHERE user_id=? 
DEBUG [main] - ==> Parameters: 2(Integer)
DEBUG [main] - <==      Total: 1
DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6c7a164b]
User(userId=2, userName=user01, userPassword=123456, userStatus=1, userIsDel=0)

我们通过IDEA的提示可以看到这些方法:

我们可以根据这些方法的描述就可以猜到大概用途了

- - - - - 添加操作 - - - - -
public boolean insert()
直接将当前实例进行SQL插入操作

public boolean insertOrUpdate()
该方法会先判断你的实例是否设置主键属性NULL,
然后再由这个结果执行插入或者更新

- - - - - 修改操作 - - - - -
public boolean updateById()
通过当前实例的ID进行更新操作

public boolean update(Wrapper<T> updateWrapper)
通过封装条件对象来执行修改操作

- - - - - 删除操作 - - - - -
public boolean deleteById(Serializable id) 
通过注入一个序列化类型的id对象来进行删除,DELETE FROM xxx WHERE xx_id = ?

public boolean deleteById()
通过当前实例的ID进行删除操作

public boolean delete(Wrapper<T> queryWrapper)
通过封装条件对象来执行删除操作,一般用于多重筛选条件的删除

- - - - - 查询操作 - - - - -
public List<T> selectAll()
通过该实例查询表的所有记录

public T selectById(Serializable id)
通过当前实例查询记录并返回此实例上

public List<T> selectList(Wrapper<T> queryWrapper)
通过给予的封转条件对象进行查询

public T selectOne(Wrapper<T> queryWrapper)
well...他们还提供了一个只查询一个的结果

public <E extends IPage<T>> E selectPage(E page, Wrapper<T> queryWrapper)
用于翻页的查询,懂的都懂,不赘述了

public Integer selectCount(Wrapper<T> queryWrapper) 
用于查询总记录数的,上面的翻页肯定套用了这个方法
放出来调用肯定还有别的需要

如果上述的情况都满足不了实际的开发需求,它们还提供了原生Session供我们单独的自己写:

关于关联查询的需求的增加字段的解决方案:

在第一阶段的项目案例中,使用的关联查询的结果集装填方案有两种:

第一种:

使用Map处理,因为A关联B,A表B表都是独立的关系,关联查询的结果集双方都缺少双方的属性

数据封装不完整,使用Map容器摆脱对象的类型限制,应收尽收,但是传递给前端就很难调用

另外非对象处理也是困难不友好的

第二种:

使用继承的方式,A继承B,A就拥有了B的所有属性,关联的结果集对象封装,A就可以完成这个任务了

但是继承之后,其他属性就为NULL,A的耦合就很大,也不是很好的解决方案

Mybatis-Plus的解决方案:

@TableField注解的一个属性exist

    @TableField(exist = false)
    private String unknowFieldInHere;

该注解表示如果SQL查询的关联结果的字段中找不到该实体类属性,会忽略掉

还是调用AR的自身ID查询:

完全没问题:

DEBUG [main] - Creating a new SqlSession
DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4c5ae43b] was not registered for synchronization because synchronization is not active
DEBUG [main] - Fetching JDBC Connection from DataSource
DEBUG [main] - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/oa?serverTimezone=GMT]
DEBUG [main] - JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@56aaaecd] will not be managed by Spring
DEBUG [main] - ==>  Preparing: SELECT user_id,user_name,user_password,user_status,user_is_del FROM sys_user WHERE user_id=? 
DEBUG [main] - ==> Parameters: 3(Integer)
DEBUG [main] - <==      Total: 1
DEBUG [main] - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4c5ae43b]
User(userId=3, userName=user02, userPassword=123456, userStatus=1, userIsDel=0, unknowFieldInHere=null)

如果是插入SQL也没问题:

DEBUG [main] - Creating a new SqlSession
DEBUG [main] - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4c5ae43b] was not registered for synchronization because synchronization is not active
DEBUG [main] - Fetching JDBC Connection from DataSource
DEBUG [main] - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/oa?serverTimezone=GMT]
DEBUG [main] - JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1a45193b] will not be managed by Spring
DEBUG [main] - ==>  Preparing: INSERT INTO sys_user ( user_name, user_password, user_status, user_is_del ) VALUES ( ?, ?, ?, ? ) 
DEBUG [main] - ==> Parameters: 阿伟001(String), 133778(String), 1(Integer), 0(Integer)
DEBUG [main] - <==    Updates: 1
原文地址:https://www.cnblogs.com/mindzone/p/13443999.html