Mybatis自动生成代码时不影响自定义语句方法

时间:2025-03-16 08:01:04

前言

在使用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<ArticleLog> 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<ArticleLog> logList);
}

新建文件,namespace改为ArticleLogExtendMapper的路径,如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/">
<mapper namespace="">
  <resultMap id="BaseResultMap" type="">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="article_id" jdbcType="INTEGER" property="articleId" />
    <result column="read_count" jdbcType="INTEGER" property="readCount" />
    <result column="invoke_res" jdbcType="VARCHAR" property="invokeRes" />
    <result column="create_date" jdbcType="TIMESTAMP" property="createDate" />
  </resultMap>
  <insert id="insertBatch" parameterType="list">
  	insert into article_log(article_id,read_count,invoke_res,create_date) values
  	<foreach collection="list" item="log" separator=",">
  		(#{,jdbcType=INTEGER},#{,jdbcType=INTEGER},
  		#{,jdbcType=VARCHAR},#{,jdbcType=TIMESTAMP})
  	</foreach>
  </insert>
</mapper>

总结

创建好扩展Mapper后,在使用的时候只需要在Service中注入ArticleLogExtendMapper即可,由于是继承关系,ArticleLogExtendMapper可以调用原mapper方法,也可以调用自定义方法。同时即使原mapper发生了变更,也不会影响到自定义语句。


???? 欢迎前往博客主页查看更多内容

???? 如果觉得不错,期待您的点赞、收藏、评论、关注

???? ​ 如有错误欢迎指正!