pojo、pojo包装类
public class User {
private int id;
private String username;
private String sex;
private Date birthday;
private String address;
//省略get/set方法
}
//继承User类
public class UserCustom extends User {
}
/*
包装类
* */
public class UserQueryVo {
private UserCustom userCustom;
private List<Integer> ids; //从pojo类中读取List
}
当paramterType是UserQueryVo时,需要取出ids的值,用foreach遍历
UserMapper.xml<sql id="findUser_where">
<if test="userCustom">
<if test="userCustom.sex != null and userCustom.sex != ''">
and sex = #{userCustom.sex}
</if>
<!--
使用foreach遍历传入的ids集合
collection:指定输入的对象中集合的属性
item:每次遍历的元素生成的对象
open:开始遍历时生成的串
close:结束遍历时生成的串
separator:遍历的两个对象中需要生成的串
-->
<if test="ids != null">
<!--最终生成的SQL语句: select * from user where sex = '' and (id= or id= or id= ) and username like '' -->
<foreach collection="ids" item="user_id" open="and (" close=")" separator="or">
<!-- 每个遍历需要生成的串 -->
id=#{user_id}
</foreach>
</if>
<!-- 与上面的foreach等价
<if test="ids != null">
最终生成的SQL语句: select * from user where sex = '' and id in(1,2,3) and username like ''
<foreach collection="ids" item="user_id" open="and id in(" close=")" separator=",">
#{user_id}
</foreach>
</if>
-->
<if test="userCustom.username != null and userCustom.username != ''">
and username like '%${userCustom.username}%'
</if>
</if>
</sql>
<select id="findUserByIds" parameterType="cn.itcast.mybatis.po.UserQueryVo" resultType="cn.itcast.mybatis.po.UserCustom">
select * from user
<!-- 最好不要将where语句包括进去 -->
<where>
<!-- 引用sql片段 ,如果refid指定的id不在本mapper中,需要指定namesapce-->
<include refid="findUser_where"></include>
</where>
</select>