1.if标签
通过if标签进行条件查找,可能是用户名,用户性别,用户年龄…
1.创建userDao的条件查询方法
List<User> findUserByCondition(User user);
2.配置userDao.xml文件
<select id="findUserByCondition" resultType="com.mybatis.beans.User" parameterType="com.mybatis.beans.User">
SELECT * FROM USER WHERE 1=1
<if test="username != null">
and username=#{username}
</if>
</select>
3.测试
@Test
public void testfindUserByCondition(){
User u = new User();
u.setUsername("老王");
List<User> users = userDao.findUserByCondition(u);
for (User user :
users) {
System.out.println(user);
}
}
2.where标签
使用where标签可以不用在sql语句中写where 1=1
<select id="findUserByCondition" resultType="com.mybatis.beans.User" parameterType="com.mybatis.beans.User">
SELECT * FROM USER
<where>
<if test="username!= null">
username= #{username}
</if>
</where>
</select>
3.foreach标签
使用foreach标签可以进行子查询,列如将id为1,2,3的信息查询出来。
1.创建UserDao的子查询方法findUserInIds
List<User> findUserInIds(QureyVo vo);
2.配置UserDao.xml
foreach标签中:
【1】collection:代表集合ids
【2】open:以open的值开头
【3】close:以close的值结尾
【4】item:遍历时的id
【5】separator:以separator的值分割
</select>
<select id="findUserInIds" resultType="com.mybatis.beans.User" parameterType="com.mybatis.beans.QureyVo">
SELECT * FROM USER
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open="and id in(" close=")" item="uid" separator=",">
#{uid}
</foreach>
</if>
</where>
</select>
3.测试
@Test
public void testfindUserInIds(){
QureyVo vo = new QureyVo();
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
vo.setIds(list);
List<User> users = userDao.findUserInIds(vo);
for (User user :
users) {
System.out.println(user);
}
}