Mybatis Plus版本升级及项目业务开发规范简要说明
码农: Alias
> 版本升级说明:此次将Mybatis Plus的版本由2.x升级到3.1.2版本,最新版本是3.2,由于3.2版本的sql分析打印插件变动需要额外配置,故暂时不升级到3.2版本(因为懒)。一.从Mybatis逆向工程说起
- MyBatis-Plus 的代码生成器可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码。执行代码生成类,生成代码,如图:
- 延用之前项目开发的规范,在我们逆向工程代码生成策略中主要有这两个:
strategy.setSuperEntityClass("xxx.xxx.dao.SuperEntity");
strategy.setSuperMapperClass("xxx.xxx.dao.SuperMapper");
strategy.setSuperServiceImplClass("xxx.xxx.service.SuperService");
前两行代码主要是用来设定生成的实体类与mapper接口的超类。其中SuperMapper继承了MP的BaseMapper类,该类已经封装了常规的CRUD方法(因此,提醒各位,DAO层常规的CRUD接口可以不必再次实现,以达到常规CRUD方法去SQL化、去XML配置化)。第三行代码主要是设置Service实现类的超类SuperService。
使用了3.1.2版本的MP生成的Service接口提供了通用 Service CRUD 封装IService接口,进一步封装 CRUD 采用 get 查询单行
remove 删除
list 查询集合
page 分页
前缀命名方式区分 Mapper
层避免混淆。如果存在自定义通用 Service 方法的可能,可以创建 IBaseService
继承 Mybatis-Plus
提供的基类。目前CMS项目的SuperService类就是自定义通用Service方法的类,我在该类的基础上继承了ServiceImpl,扩展了ServiceImpl提供的功能。
-
Service样例代码
/** * <p> * 文章内容扩展表,增加扩展字段 服务类 * </p> * * @author alias * @since 2019-12-05 */ public interface IInfoExtendService extends IService<InfoExtend> { }
接着我们看看Service接口实现类,该类继承了SuperService类差不多。该类也聚合BaseMapper、ServiceImpl等类的功能。
- ServiceImpl源码:
@SuppressWarnings("unchecked")
public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
protected Log log = LogFactory.getLog(getClass());
@Autowired
protected M baseMapper;
.....
}
-
Service实现类样例代码:
/** * <p> * 文章内容扩展表,增加扩展字段 服务实现类 * </p> * * @author alias * @since 2019-12-05 */ @Service public class InfoExtendServiceImpl extends SuperService<InfoExtendMapper, InfoExtend> implements IInfoExtendService { }
-
SuperService源码: