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代码:
由于在DAO接口中使用注解,将入参绑定到@Param注解的同名参数上,所以在xml代码中,就可以使用#{参数名}的方法取得各个参数。
这种情况下,select标签上也不用声明parameterType了。
方案二、使用map封装参数
DAO接口代码:
List<User> listByCondition(HashMap map);
xml代码:
这种方法是将参数先放入哈希表中,然后统一传递给DAO方法。
xml文件中,需要指定parameterType="hashmap",hashmap是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框架已经配置好的类型,可以直接使用。
相关文章推荐
- SSM框架day02-MyBatis——066——动态SQL查询、067 MyBatis注解-动态SQL增删改、068 MyBatis注解-动态SQL的SQL类
- SSM框架day02-MyBatis——034——符合查询问题演示、035——动态SQL
- SSM框架实战系列之十一_MyBatis框架之DAO代码
- SSM框架实战系列之十_MyBatis框架
- Spring+SpringMVC+Mybatis整合系列(三)SSM框架整合
- SSM-MyBatis框架关联查询实例二
- SSM框架下实现MyBatis连接查询,一对多和多对一
- SSM框架中mybatis采用动态传入表名的方法
- SSM系列1:简易详细的(Spring +Springmvc+Mybatis)框架整合搭建
- SSM框架实战系列之四_第一个Maven项目
- SSM框架之MyBatis(二)--多表查询及查询结果映射
- SSM框架 Mybatis联合查询 多表查询 分页
- ssm框架学习---mybatis中一对多关系的查询
- 【SSM-MyBatis框架】关联查询--多对多查询
- SSM框架实战系列之三_Maven之二
- 21、SSM框架-Mybatis多参数查询与列表查询不同方式实现(3)
- SSM框架笔记04:MyBatis关联数据查询
- 框架学习系列 mybatis 第十四篇 mybatis动态sql一
- mybatis实战之路,疯狂的数据库操作框架、动态sql的mybats之快速搭建基本环境
- ssm框架学习---mybatis中动态sql中的if片段