MyBatis框架之sql动态查询
-
动态sql之if标签与where标签
if标签的 test 属性中写的是对象的属性名,
where标签用来简化开发
1.定义持久层接口Dao
public interface IUserDao {
List<User> findUserByCondition(User user);
}
2.配置xml文件
<select id="findUserByCondition" resultType="user" parameterType="user">
select * from user
<where>
<if test="username!=null">
and username=#{username}
</if>
<if test="sex!=null">
and sex=#{sex}
</if>
</where>
</select>
3.编写测试类
@Test
public void testfindByCondition() {
User u = new User();
u.setUsername("李");
u.setSex("女");
List<User> users = userDao.findUserByCondition(u);
for (User user : users) {
System.out.println(user);
}
}
-
foreach标签
标签用于遍历集合,它的属性:
collection:代表要遍历的集合元素,注意编写时不要写#{}
open:代表语句的开始部分
close:代表结束部分item:代表遍历集合的每个元素,生成的变量名
sperator:代表分隔符1.定义持久层接口Dao
List<User> findUserInIds(QueryVo vo);
2.配置xml文件
<select id="findUserInIds" resultType="user" parameterType="cn.xiong.domain.QueryVo"> select * from user <where> <if test="ids!=null and ids.size()>0"> <foreach collection="ids" open="and id in (" close=")" item="id" separator=","> #{id} </foreach> </if> </where> </select>
3.测试类
@Test public void testfindUserInIds(){ QueryVo vo = new QueryVo(); List<Integer> list =new ArrayList<Integer>(); list.add(41); list.add(43); list.add(50); list.add(51); vo.setIds(list); List<User> users = userDao.findUserInIds(vo); for (User user : users) { System.out.println(user); } }