在使用mybatis的过程中,如果数据结构发生变更,需要重新生成domain、mapper等文件,生成的时候默认是追加到原文件后面,应该可以配置成覆盖原文件,具体方法暂时未找到,有知道的小伙伴可以在评论区交流。
不论是追加还是覆盖,如果有自定义的sql语句,这时候会极其不方便,需要将自定义语句copy出来,重新生成完再copy进去。本文介绍的是新增一个扩展Mapper文件,继承原来的Mapper,在扩展Mapper文件里写自定义sql语句,这样即使原来的Mapper文件被覆盖也不会影响到自定sql语句
实现方法原mapper如下
public interface ArticleLogMapper {
long countByExample(ArticleLogExample example);
int deleteByExample(ArticleLogExample example);
int deleteByPrimaryKey(Integer id);
int insert(ArticleLog record);
int insertSelective(ArticleLog record);
List selectByExample(ArticleLogExample example);
ArticleLog selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") ArticleLog record, @Param("example") ArticleLogExample example);
int updateByExample(@Param("record") ArticleLog record, @Param("example") ArticleLogExample example);
int updateByPrimaryKeySelective(ArticleLog record);
int updateByPrimaryKey(ArticleLog record);
}
新建一个mapper,继承原mapper并在其中添加自定义语句
public interface ArticleLogExtendMapper extends ArticleLogMapper {
void insertBatch(List logList);
}
新建Mapper.xml文件,namespace改为ArticleLogExtendMapper的路径,如下:
总结insert into article_log(article_id,read_count,invoke_res,create_date) values (#{log.articleId,jdbcType=INTEGER},#{log.readCount,jdbcType=INTEGER}, #{log.invokeRes,jdbcType=VARCHAR},#{log.createDate,jdbcType=TIMESTAMP})
创建好扩展Mapper后,在使用的时候只需要在Service中注入ArticleLogExtendMapper即可,由于是继承关系,ArticleLogExtendMapper可以调用原mapper方法,也可以调用自定义方法。同时即使原mapper发生了变更,也不会影响到自定义语句。



