1 需求
实现多条件查询用户
- 姓名模糊匹配
- 年龄在指定的最小值到最大值之间
2 准备表和数据
create table d_user(id int primary key auto_increment,name varchar(10),age int(3));insert into d_user(name,age) values('Tom',12);insert into d_user(name,age) values('Bob',13);insert into d_user(name,age) values('Jack',18);
3 ConditionUser(查询条件实例类)
private String name;private int minAge;private int maxAge;
4 userMapper.xml(映射文件)
<mapper namespace="cn.imentors.mybatis.test7.userMapper"><!--实现多条件查询用户(姓名模糊匹配, 年龄在指定的最小值到最大值之间)--><select id="getUser" parameterType="ConditionUser" resultType="User">select * from d_user where<if test='name != "%null%"'>name like #{name} and</if>age between #{minAge} and #{maxAge}</select></mapper>
5 测试
@Testpublic void test(){SqlSessionFactory factory = MybatisUtils.getFactory();SqlSession session = factory.openSession();String statement = "cn.imentors.mybatis.test7.userMapper.getUser";String name = "o";name = null;ConditionUser parameter = new ConditionUser("%"+name+"%", 13, 18);List<User> list = session.selectList(statement, parameter);System.out.println(list);session.close();
6 MyBatis中可用的动态SQL标签
6.1 if
6.2 choose
<select id=”findActiveBlogLike”parameterType=”Blog” resultType=”Blog”>SELECT * FROM BLOG WHERE state = „ACTIVE‟<choose><when test=”title != null”>AND title like #{title}</when><when test=”author != null and author.name != null”>AND title like #{author.name}</when><otherwise>AND featured = 1</otherwise></choose></select>
6.3 where
<select id=”findActiveBlogLike” parameterType=”Blog” resultType=”Blog”>SELECT * FROM BLOG<where><if test=”state != null”>state = #{state}</if><if test=”title != null”>AND title like #{title}</if><if test=”author != null and author.name != null”>AND title like #{author.name}</if></where></select>
6.4 set
<update id="updateAuthorIfNecessary"parameterType="domain.blog.Author">update Author<set><if test="username != null">username=#{username},</if><if test="password != null">password=#{password},</if><if test="email != null">email=#{email},</if><if test="bio != null">bio=#{bio}</if></set>where id=#{id}</update>
6.5 foreach
<select id="selectPostIn" resultType="domain.blog.Post">SELECT *FROM POST PWHERE ID in<foreach item="item" index="index" collection="list"open="(" separator="," close=")">#{item}</foreach></select>
注:你可以传递一个List实例或者数组作为参数对象传给MyBatis。当你这么做的时候,MyBatis会自动将它包装在一个Map中,用名称作为键。List实例将会以“list”作为键,而数组实例将会以“array”作为键
捐赠我们
良师益友工作室一直在致力于帮助编程爱好更加快速方便地学习编程,如果您对我们的成果表示认同并且觉得对你有所帮助,欢迎您对我们捐赠^_^。 
良师益友工作室一直在致力于帮助编程爱好更加快速方便地学习编程,如果您对我们的成果表示认同并且觉得对你有所帮助,欢迎您对我们捐赠^_^。
