MyBatis多参数绑定的另一种方式

不同的MyBatis的多参数绑定

Posted by yyconstantine on October 24, 2019

MyBatis多参数绑定的另一种方式

传统使用MyBatis进行多参数绑定时,要对所有的参数建立绑定关系。

如今,使用Java8的-parameters参数,使Mapper代码更加简洁。


传统的多参数绑定

举一个项目中的不恰当的例子(正确做法是将多个参数封装为实体):

int updateAccountDetails(@Param("insid") String insid,
                         @Param("rspcode") String rspcod,
                         @Param("rspmsg") String rspmsg,
                         @Param("status") String status,
                         @Param("obssid") String obssid);

问题:如果我们不使用实体进行数据传输,则我们需要对所有的实体增加@Param(value = "")进行MyBatis的参数绑定,代码会非常啰嗦。

一般情况下,如果我们选择不在这里做参数绑定,则我们需要在mapper.xml中做出这样的妥协:

update test_tbl <trim prefix="set" suffixOverrides=",">
		<if test="status!=null">status=#{param4},</if>
		<if test="rspcode!=null">rspcode=#{param2},</if>
		<if test="rspmsg!=null">rspmsg=#{param3},</if>
		<if test="obssid!=null">obssid=#{param5},</if>
		MODIFIED_DATE=sysdate
		</trim>
		where account_no=#{param1}

问题:如果不在Mapper.java做参数绑定,则mapper.xml中的代码会让人十分迷惑,不利于代码规范


新的多参数绑定

PS:基于JDK8与MyBatis3.4.1及更新的版本

我们的Mapper.java更改为如下:

int updateAccountDetails(String insid,
                         String rspcod,
                         String rspmsg,
                         String status,
                         String obssid);

我们的mapper.xml更改为如下:

update test_tbl <trim prefix="set" suffixOverrides=",">
		<if test="status!=null">status=#{status},</if>
		<if test="rspcode!=null">rspcode=#{rspcode},</if>
		<if test="rspmsg!=null">rspmsg=#{rspmsg},</if>
		<if test="obssid!=null">obssid=#{obssid},</if>
		MODIFIED_DATE=sysdate
		</trim>
		where account_no=#{insid}

去除了参数绑定是第一步,另外,我们需要在pom.xml文件中增加插件:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-compiler-plugin</artifactId>
   <version>3.8.0</version>
   <configuration>
       <compilerArgument>-parameters</compilerArgument>
       <encoding>UTF-8</encoding>
   </configuration>
</plugin>

以及开启MyBatis配置:

mybatis:
  configuration:
    use-actual-param-name: false

这样,我们就可以不使用@Param(value = "xxx")进行参数绑定了!

另外,实测发现,新版本的IDEA或Eclipse并不需要进行上述插件和配置的操作,正常使用Maven打包即可,不需要开启任何插件或指令或配置


最后

这个问题的原因来自于,我之前一直在写公司Hibernate的项目,MyBatis很久不用,忘记多参数要加注解绑定了,但是一直没加也没报错,昨晚上到预发后报了参数绑定错误,但自己本地或测试环境一直正常,最后发现是上预发的人的Eclipse的2015年10月的release,那时候估计Java8的这个特性还没有,所以不支持吧~

所以,还是要勇于走出舒适圈,多探索才能了解更多的东西啊(不要脸的夸夸自己