时间:2021-07-01 10:21:17 帮助过:2人阅读
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);
private String name;private int minAge;private int maxAge;
<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>
@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();
<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>
<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>
<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>
注:你可以传递一个List实例或者数组作为参数对象传给MyBatis。当你这么做的时候,MyBatis会自动将它包装在一个Map中,用名称作为键。List实例将会以“list”作为键,而数组实例将会以“array”作为键
<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>

07_动态SQL与模糊查询
标签: