Mybatis IF
如果表(Product)的字段比較多的話,爲了應付各個字段的查詢,那麼就需要寫多條sql語句,這樣就變得難以維護。
這個時候,就可以使用Mybatis 動態SQL裏的if標籤。
當mapper中的parametType爲基本類型(如int,string等)時,是怎樣使用的
最簡單的使用方法:
<select id="list" parameterType="string" resultMap="ClassroomResultMap">
select id, name
from bc
where name = #{name}
</select>
這裏的參數#{}中寫什麼變量名都可以,mybatis會自動給賦值。而當使用if語句時,比如
<select id="list" parameterType="string" resultMap="ClassroomResultMap">
select id, name
from bc
<where>
<if test="name != null and <span style="font-family: Arial, Helvetica, sans-serif;">name</span> != ''">
name like CONCAT('%','${name}','%')
</if>
</where>
</select>
會報錯
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named ‘name’ in ‘class java.lang.String’
原因:
mybatis自動調用OGNL尋找String的name屬性
解決辦法:
1、使用_parameter
<select id="list" parameterType="string" resultMap="ClassroomResultMap">
select id, name
from bc
<where>
<if test="_parameter != null and _parameter != ''">
name like CONCAT('%','${name}','%')
</if>
</where>
</select>
2、使用mybatis默認的對象名:value
<select id="list" parameterType="string" resultMap="ClassroomResultMap">
select id, name
from bc
<where>
<if test="value != null and value != ''">
name like CONCAT('%','${value}','%')
</if>
</where>
</select>