动态sql
mybaits核心对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接,组装
- 需求:用户信息的综合查询列表和用户信息列表总数这两个Statement的定义使用动态sql对查询条件进行判断,如果输出参数不为空,才进行查询条件的拼接
定义sql片段
<sql id="query_user_where">
<if test ="userCustom!=null">
<if test = "userCustom.sex!=null and userCustom.sex!= ''">
and user.sex = #{userCustom.sex}
</if>
<if test = "userCustom.name!=null and userCustom.name!= ''">
and user.name = #{userCustom.name}
</if>
</if>
</sql>
引用sql片段
select * from user
<!-- where可以自动去掉条件中的第一个and -->
<where>
<!-- 引用sql片段的id,如果refid指定的id不在本mapper文件中,需要前边加namespace -->
<include refid = "query_user_where"></include>
<!-- 在这里还要引用其他的sql片段 -->
</where>
foreach
向sql传递数组或list,mybaits使用foreach解析
- 需求:在用户查询列表和总数中增加多个id的查询
id=1 OR id=2
- 在输入的参数类型中添加Listids 传入多个id
//传入多个id
private List<Integer> ids;
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
- xml文件
<if test = "ids!=null">
<!-- 使用foreach遍历传入ids
collection:指定输入对象中集合属性
item:每个遍历生成对象
open:开始遍历拼接的串
close:结束遍历拼接的串
separator:遍历的两个对象中需要拼接的串
-->
<!-- 使用实现下边的sql拼接
AND (id=1 OR id=2 OR id=3)
-->
<foreach collection = "ids" item = "user_id" open = "AND (" close = ")" separator = "OR">
<!-- 每次遍历需要拼接的串 -->
id = #{user_id}
</foreach>
</if>
- 测试
@Test
public void testFindUserList() throws Exception {
SqlSession sqlSession = SqlSessionFactory.openSession();
//创建UserMapper对象,mybaits自动生成mapper代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//SqlMapConfig加载映射文件
//创建包装对象,设置查询条件
UserQueryVo userQueryVo = new UserQueryVo();
UserCustom userCustom = new UserCustom();
//由于这里使用动态sql,如果不设置某个值,条件不会拼接在sql中
//userCustom.setSex("男");
userCustom.setName("小明");
//传入多个id
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
//将ids通过userQueryVo传入Statement中
userQueryVo.setIds(ids);
userQueryVo.setUserCustom(userCustom);
//调用userMapper方法
List<UserCustom> list = userMapper.findUserList(userQueryVo);
sqlSession.close();
System.out.println(list);
}