您的位置:首页 > 编程语言 > Java开发

SSM框架实战系列之十二_MyBatis框架之动态查询

2017-12-08 10:25 411 查看
  SSM框架实战系列之十二_MyBatis框架之动态查询

  在上一讲中我们提到了MyBatis中的查询。

  在查询时,可以通过parameterType指定传入参数的类型。

  例如根据id查找对象时,可以将parameterType设置为java.lang.Integer,表示传入一个整数类型的id。

  有时,在查询中需要传入多个条件,例如:



  在上图中,可以根据用户名查询,可以根据真实姓名查询,还可以只显示启用中的用户,因此查询条件有多个。

  这种情况下,就要考虑一下怎么做了。

  方案一、使用注解实现参数绑定

  DAO接口代码:

  List<User> listByCondition(@Param("name") String name, @Param("realName") String realName, @Param("isUse") boolean isUse);

  xml代码:

<select id="list" resultMap="BaseResultMap">
select user_id,
<include refid="dataFields" />
from tbl_user
where is_del = 0
<if test="name != null and name != ''">
and user_name like concat(concat('%', #{name}), '%')
</if>
<if test="realName != null and realName != ''">
and real_name like concat(concat('%', #{realName}), '%')
</if>
<if test="isUse">
and is_use = 1
</if>
</select>


  由于在DAO接口中使用注解,将入参绑定到@Param注解的同名参数上,所以在xml代码中,就可以使用#{参数名}的方法取得各个参数。

  这种情况下,select标签上也不用声明parameterType了。

  方案二、使用map封装参数

  DAO接口代码:

  List<User> listByCondition(HashMap map);

  xml代码:

<select id="list" parameterType="hashmap" resultMap="BaseResultMap">
select user_id,
<include refid="dataFields" />
from tbl_user
where is_del = 0
<if test="name != null and name != ''">
and user_name like concat(concat('%', #{name}), '%')
</if>
<if test="realName != null and realName != ''">
and real_name like concat(concat('%', #{realName}), '%')
</if>
<if test="isUse">
and is_use = 1
</if>
</select>


  这种方法是将参数先放入哈希表中,然后统一传递给DAO方法。

  xml文件中,需要指定parameterType="hashmap",hashmap是MyBatis框架已经配置好的类型,可以直接使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring springmvc mybatis