(一)if 和 where
<!--where会自动处理if标签里面的第一个and不会处理之后if里的and--> <select id="queryPersonBySexName" resultType="Person" parameterType="Person"> select id,name,sex from person <where> <if test="name!=null and name!=''"> and name = #{name} </if> <if test="sex!=null"> and sex = #{sex,javaType=boolean , jdbcType = VARCHAR} </if> </where> </select>
测试方法:
/*通过if语句来传参*/ Person person = new Person(); person.setSex(true); person.setName("陈勇丞"); Person person1 = mapper.queryPersonBySexName(person); System.out.println(person1);
(二)列表循环查询
<--循环查询 列表查询 separator分隔符--> <select id="queryPersonForById" parameterType="java.util.List" resultType="Person"> select * from person <where> <if test="list!=null and list.size>0"> <foreach collection="list" open=" and id in(" close=")" item="id" separator=","> #{id} </foreach> </if> </where> </select>
测试方法:
/*列表循环查询*/ List<Integer> List = new ArrayList<>(); List.add(1); List.add(2); List.add(5); List<Person> list1 = mapper.queryPersonForById(List); System.out.println(list1);
(三)简单数组查询
<!--循环 简单数组查询 要用array来代替-->
<select id="queryPersonForById" parameterType="int[]" resultType="Person">
select * from person
<where>
<if test="array!=null and array.length">
<foreach collection="array" open=" and id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
测试方法:
/*简单数组循环查询*/ int []a={1,2,5}; List<Person> people = mapper.queryPersonForById(a); System.out.println(people);
(四) 对象数组
<!--循环 对象数组 parameterType="Object[]" item="对象名"--> <select id="queryPersonForById" parameterType="Object[]" resultType="Person"> select * from person /*导入sql如果在其他的包 需要先在config加载 在用命名空间.sql的id*/ <include refid="com.xiaonuo.Interface.abc.queryByIdPersonArray" /> </select>
测试方法:
/*对象数组循环查询*/ Person person1 = new Person(); person1.setId(1L); Person person2 = new Person(); person2.setId(2L); Person person3 = new Person(); person3.setId(5L); Person []persons = {person1,person2,person3}; List<Person> people = mapper.queryPersonForById(persons); System.out.println(people);
(五)map查询
<!--循环 map collection取的是键名-->
<select id="queryPersonForById" parameterType="java.util.HashMap" resultType="Person">
select * from person
<where>
<if test="list!=null">
<foreach collection="list" open=" and id in(" close=")" item="item" separator=",">
#{item.id}
</foreach>
</if>
</where>
</select>
测试方法:
/*map查询*/ Person person1 = new Person(); person1.setId(1L); Person person2 = new Person(); person2.setId(2L); Person person3 = new Person(); person3.setId(5L); List<Person> list1 = new ArrayList<>(); list1.add(person1); list1.add(person2); list1.add(person3); Map map = new HashMap(); map.put("list",list1); List<Person> people = mapper.queryPersonForById(map); System.out.println(people);