天天看点

【测试开发】使用 Mybatis-Plus 的 BaseMapper 接口与 Service 接口

最近在工作开发中遇到一个批量新增修改的处理,我使用的是 mybatis-plus,但是在用的 BaseMapper 接口里是没有这个方法的,后来发现 Service 接口里有这个方法,今天整理一下这2种用法。

一、使用 BaseMapper 接口

MyBatis Plus 提供了通用的 Mapper 接口(即 BaseMapper 接口),该接口对应我们的 DAO 层。在该接口中,定义了我们常见的方法签名,这样就可以方便我们对表进行操作。例如:查询(select)、插入(insert)、更新(update)和删除(delete)操作。

以为项目中的代码为例,我有一个实体类

User

,需要对其进行CRUD,那么我直接在 DAO 层去继承 BaseMapper 接口即可。

@Mapper
public interface UserMapper extends BaseMapper<User> {
}
           

这样我就可以直接使用里面的各种API了,非常的方便。另外,我发现了一个mybatis-plus的简洁教程,可以很方便的查询一些知识点,文末自取。

【测试开发】使用 Mybatis-Plus 的 BaseMapper 接口与 Service 接口

但是后来在开发过程中,发现

BaseMapper

接口中的

insert()

不能满足我的需求了,而在

Service

接口中,发现有个

saveOrUpdateBatch()

可以使用,果断拥抱之。

二、使用 Service 接口

除了 BaseMapper 接口,MyBatis Plus 还提供了 IService 接口,该接口对应 Service 层。MyBatis Plus 的通用 Service CRUD 实现了 IService 接口,进一步封装 CRUD。为了避免与 BaseMapper 中定义的方法混淆,该接口使用 get(查询单行)、remove(删除)、list(查询集合)和 page(分页)前缀命名的方式进行区别。

这个既然是对应 Service 接口,那么也就要用在 service 层。

还是要处理刚才的

User

类,DAO 层仍然是需要的:

@Mapper
public interface AddressListMapper extends BaseMapper<User>{

}
           

然后在 service 层的接口继承

IService

,泛型是

User

实体类:

public interface AddressListService extends IService<User> {
    /**
     * 同步用户信息到数据库
     */
    void saveUsers();
}
           

最后在 service 的实现层中,继承

ServiceImpl

,泛型中传入

mapper

和实体类:

@Service
public class AddressListServiceImpl extends ServiceImpl<AddressListMapper, User> implements AddressListService {

}
           

现在就可以使用 mybaits-plus service接口中提供的api了。

【测试开发】使用 Mybatis-Plus 的 BaseMapper 接口与 Service 接口

我使用的是

saveOrUpdateBatch

,这个要注意下,是通过自定义的唯一索引进行批量保存更新的,所以我要去实体类

User

中使用

@TableId

标记出唯一索性。

/**
     * 邮箱
     */
    @TableId
    private String email;
           

最后,放上教程链接:https://www.hxstrive.com/subject/mybatis_plus/257.htm

--不要用肉体的勤奋,去掩盖思考的懒惰--