时间:2021-07-01 10:21:17 帮助过:4人阅读
目录
当你要查询的参数不确定时:参数可能只有username或者password或者有多个甚至什么都没有
test 类
@Test
public void testFindByCondition(){
User u=new User();
u.setUsername("醉人");
List<User> users=userMapping.findUserByCondition(u);
for (User user:users){
System.out.println(user);
}
}
mapping.xml(大小写、名称一致很重要)
<!--根据条件查询-->
<select id="findUserByCondition" resultType="domain.User">
select *from user where 1=1
/*username应该与实体表中的名字一致,包括大小写*/
<if test="username!=null">
/*#{username} 应该与实体表中的名字一致,包括大小写*/
and username=#{username}
</if>
<if test="id!=null">
and id =#{id}
</if>
</select>
<select id="findUserByCondition" resultType="domain.User">
select *from user
<where>
<if test="username!=null">
and username=#{username}
</if>
<if test="id!=null">
and id=#{id}
</if>
</where>
</select>
用 where 的话比只有 if 的 sql 语句更简洁
select *from user where id in(1,2)
<select id="findUserInIds" resultType="domain.User">
select *from user
<where>
<if test="list !=null and list.size()>0">
<foreach collection="list" item="item" open="and id in(" close=")" separator=",">
#{item}
</foreach>
</if>
</where>
</select>
@Test
public void testFindUserInIds(){
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(1);
list.add(2);
List<User> users=userMapping.findUserInIds(list);
for (User user:users){
System.out.println(user);
}
}
<sql id="defaultUser">
select *from user
</sql>
调用
注意:如果后面还要添加语句,上面的 sql 语句后面不要添加分号
<select id="findAll" resultType="domain.User">
<include refid="defaultUser"/>
/*select *from user;*/
</select>
10-动态SQL语句
标签:list reac 动态sql 条件 HERE 调用 word use sele