这些都是搞开发老生长谈的事了,老是犯同样的错,今天记录下:比较消息的mybatis中传入String类型参数的问题

  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方法

  1. 解决办法
    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能传多个这样的参数

转载:http://www.tofacebook.com/jinjiezhimei.html
发布了12 篇原创文章 · 获赞 9 · 访问量 895

猜你喜欢

转载自blog.csdn.net/cyhlili100/article/details/104006660