Jakim
Jakim

Reputation: 1813

How to avoid getters when using mybatis dynamic sql?

In mybatis we can write an update statement like this:

<update id="update" parameterType="com.test.User">
  update USERS
  <set>
    <if test="user.name != null">NAME=#{user.name},</if>
    <if test="user.age != null">AGE=#{user.age}</if>
  </set>
</update>

Then it requires User class to have getters for name and age properties, without the update statement, the mapping can work without adding any getters, is there a way to avoid the getters for the update statement?

Upvotes: 0

Views: 319

Answers (1)

ave
ave

Reputation: 3594

It should work if you use the latest version 3.5.1 (the change was made in 3.5.0).

If you cannot upgrade for some reason, it may still work if you 1) remove the @Param("user") from the method parameter and 2) reference the fields directly as follows.

<update id="update">
  update USERS
  <set>
    <if test="name != null">NAME=#{name},</if>
    <if test="age != null">AGE=#{age}</if>
  </set>
</update>

The direct property reference works only when the bean (i.e. User) is the only parameter to the mapper method.

Upvotes: 1

Related Questions