转载

mybatis-plus 的一种很别扭的用法

熟悉 mybatis-plus 的人都知道,mybatis-plus 提供两种包含预定义增删改查操作的接口:

com.baomidou.mybatisplus.core.mapper.BaseMapper
com.baomidou.mybatisplus.extension.service.IService

对比这两个接口,操作都差不多,名字有一点点改变,比如 BaseMapper 里面叫 insert() 的方法,在 IService 里面叫 save()。

其实我也不是很清楚为什么要单独设计 IService 接口,但是两者确实有区别,就是 IService 提供批处理操作, BaseMapper 没有。

另外, IService 的默认实现 com.baomidou.mybatisplus.extension.service.impl.ServiceImpl 就是调用 BaseMapper 来操作数据库,所以我猜 IService 是 Java 8 之前对 BaseMapper 所做的扩展,而 Java 8 之后,因为有了 default 方法, ServiceImpl 里面的东西其实都可以移到 BaseMapper 里面了。

除此之外还有就是 IService 依赖于 Spring 容器,而 BaseMapper 不依赖; BaseMapper 可以继承并添加新的数据库操作, IService 要扩展的话还是得调用 Mapper,显得有些多此一举。

所以,如果你既要使用批处理操作,又要添加自己的数据库操作,那就必须两个接口一起用。

比如在下面一个示例项目中,就同时存在两者:

// StudentService.java
@Service
public class StudentService extends ServiceImpl<StudentMapper, Student> {
}

// StudentMapper.java
@Component
public interface StudentMapper extends BaseMapper<Student> {

    @Select("select * from STUDENT where FIRST_NAME=#{firstName}")
    List<Student> selectByFirstName(@Param("firstName") String firstName);
}

这样每个实体都要创建两个文件,很麻烦。可不可以简化呢?可以,就像下面这样:

// StudentService.java
@Service
public class StudentService extends ServiceImpl<StudentMapper, Student> {

    public interface StudentMapper extends BaseMapper<Student> {

        @Select("select * from STUDENT where FIRST_NAME=#{firstName}")
        List<Student> selectByFirstName(@Param("firstName") String firstName);
    }
}

对,你没看错,就把 Mapper 直接写在 Service 里面就好。有人就会问了,这个 Mapper 能用吗?告诉你,能:

@Autowired
StudentService.StudentMapper studentMapper;

像上面这样引用过来,照常使用即可。

另外还有一种方式就是通过 Service 把 Mapper 暴露出来:

public class StudentService extends ServiceImpl<StudentMapper, Student> {
    
    public StudentMapper getMapper() {
        return this.baseMapper;
    }
    
    ...

这个 baseMapper 也是 StudentMapper 的实例。这样的话,使用的时候就只需要引用 StudentService 一个对象了:

List list = studentService.getMapper().selectByFirstName("First");
原文  https://segmentfault.com/a/1190000018509814
正文到此结束
Loading...