MyBatis-Plus在 MyBatis 基础上简化开发、提高开发效率,其中在Service层也做了简化操作,Service层通过继承ServiceImpl类和IServer接口可以实现简单的增删改查操作,具体操作如下:
//Service层继承ServiceImpl
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
ServiceImpl类需要接收两个泛型对象,其中UserMapper对象实现对持久层的操作,User是实体类对象,我们可以看一下源码:
public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
protected Log log = LogFactory.getLog(this.getClass());
@Autowired
protected M baseMapper;
public ServiceImpl() {
}
public M getBaseMapper() {
return this.baseMapper;
}
@Transactional(
rollbackFor = {Exception.class}
)
public boolean saveBatch(Collection<T> entityList, int batchSize) {
String sqlStatement = this.sqlStatement(SqlMethod.INSERT_ONE);
return this.executeBatch(entityList, batchSize, (sqlSession, entity) -> {
sqlSession.insert(sqlStatement, entity);
});
}
/*.....代码省略......*/
}
注意: 泛型M做了限制操作,传递的类必须是BaseMapper的子类或自身才行,关于BaseMapper的操作会在下一章节学习
ServiceImpl类完成对IServer接口的实现,在IServer接口里面有default修饰符修饰默认方法。具体如下:
public interface IService<T> {
//保存
default boolean save(T entity) {
return SqlHelper.retBool(this.getBaseMapper().insert(entity));
}
//批量保存
@Transactional(
rollbackFor = {Exception.class}
)
default boolean saveBatch(Collection<T> entityList) {
return this.saveBatch(entityList, 1000);
}
//批量保存
boolean saveBatch(Collection<T> entityList, int batchSize);
default boolean removeById(Serializable id) {
return SqlHelper.retBool(this.getBaseMapper().deleteById(id));
}
/*.....代码省略......*/
}
ServiceImpl类已完成对IServer接口方法实现,包含基础的增删改查逻辑操作,
在日常开发过程中,如果没有复杂的业务逻辑,我们可以直接在Service层继承ServiceImpl类,减少代码量,提升开发效率。
本文暂时没有评论,来添加一个吧(●'◡'●)