Common problems and solutions when MyBatis parameter type is String

  • 2020-06-15 09:05:18
  • OfStack

1. Interpolation problem when the parameter is String

Suppose you have the following 1Dao interface method


public Account findByAccountType (String type)throws DaoException;

The corresponding Mapper xml


<select id="findByAccountType " parameterType="string" resultType="account">
  select *
  form account
  <where>
    <if test ="type != null">
      type=#{type}
    </if>
  </where>
</select>

1 Generally we write in this way, which is true for other types, but for String it throws the following exception:

There is no getter for property named 'type ' in 'class java.lang.String'

Because MyBatis requires that if the parameter is String, no matter what the parameter of the interface method is, the reference in ES21en.xml needs to be changed to _parameter to be recognized:


<select id="findByAccountType " parameterType="string" resultType="account">
  select *
  form account
  <where>
    <if test ="_parameter!= null">
      type=#{_parameter}
    </if>
  </where>
</select>

2. Comparing string parameters for equality

Error:


<if test="_parameter == '1' ">
  type=#{_parameter}
</if>

Correct:


<if test='_parameter == "1" '>
  type=#{_parameter}
</if>
<if test="_parameter == '1'.toString() ">
  type=#{_parameter}
</if>

Note: The above questions are not limited to < if > Tags, other dynamic sql tags have the same problem when processing String.


Related articles: