1. 出現的問題
需求是想寫一個按公司名字查詢公司列表的功能,最開始的代碼如下
Dao層接口如下
@MyBatisDao public interface OfficeDao extends TreeDao<Office> { List<Office> findCompanyNameList(String name); }
mybatis的xml代碼:
<select id="findCompanyNameList" parameterType="java.lang.String" resultType="com.pds.modules.sys.entity.Office"> SELECT id,name FROM sys_office where o.del_flag = '1' <if test="name!= null and name!= ''"> AND name LIKE concat('%',#{name},'%') </if> </select>
這樣寫會報錯,大體意思是name沒有Getter方法。
2. 解決辦法
2.1 解決辦法1
在接口參數里加上mybatis中的@param注解
@MyBatisDao public interface OfficeDao extends TreeDao<Office> { List<Office> findCompanyNameList(@Param("name")String name); }
<select id="findCompanyNameList" parameterType="java.lang.String" resultType="com.pds.modules.sys.entity.Office"> SELECT id,name FROM sys_office where o.del_flag = '1' <if test="name!= null and name!= ''"> AND name LIKE concat('%',#{name},'%') </if> </select>
2.2 解決辦法2
在xml的if里用”_parameter” 代表參數
<select id="findCompanyNameList" parameterType="java.lang.String" resultType="com.pds.modules.sys.entity.Office"> SELECT id,name FROM sys_office where o.del_flag = '1' <if test="_parameter!= null and _parameter!= ''"> AND name LIKE concat('%',#{name},'%') </if> </select>
2.3 兩種方法區別
可以看出,_parameter不能區分多個參數,而@param能。所以@param能傳多個這樣的參數