MyBatis中使用bind標籤構造模糊查詢失敗的解決方法
阿新 • • 發佈:2019-01-06
下面的這個寫法為什麼不能成功:
<select id="findUserByFuzzyEmail" resultMap="BaseResultMap"
parameterType="com.keymen.entity.User">
<bind name="email" value="'%' +email + '%'" />
select id,username,email,status,createtime,updatetime from tb_user
where
<if test="email != null and email != ''" >
email like ${email}
</if>
</select>
異常提示:
Exception in thread "main" org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'email' in 'class java.lang.String'
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:75 )
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:371)
at com.sun.proxy.$Proxy16.selectList(Unknown Source)
後續程式碼省略...
為什麼呢?
問題需要這樣來解決:
在user.xml檔案中做出如下改的:
注意:
parameterType使用了java.lang.String型別
bind標籤的value值得寫法:value="'%'+_parameter.getEmail() +'%'"
SQL語句中使用:
email like #{pattern}
,注意是#,而不是$ 最後,測試時使用的程式碼也需要注意。
<select id="findUserByFuzzyEmail" resultMap="BaseResultMap"
parameterType="java.lang.String">
select id,username,email,status,createtime,updatetime from tb_user
<bind name="pattern" value="'%'+_parameter.getEmail() +'%'" />
<where>
<if test="email != null and email != ''">
email like #{pattern}
</if>
</where>
</select>
呼叫時,使用的測試程式碼:
userTest是User類的一個物件
List<User> userListByEmail = userServiceImpl.findUserByFuzzyEmail(userTest);
查詢獲得了正確的結果。