int selCountByCondition(User user);
<select id="selCountByCondition" resultType="java.lang.Integer">
select count(1) from tb_user
<where>
<if test="realname!=null and realname!=''">
<bind name="realname" value="'%' + realname + '%'" />
and realname like #{realname}
</if>
<if test="age!=null">
and age >#{age}
</if>
</where>
</select>
- [DEBUG] ==> Preparing: select count(1) from tb_user WHERE realname like ? and age >?
- [DEBUG] ==> Parameters: %胡%(String), 15(Integer)
- [DEBUG] <== Total: 1
分为三部分,第一部分是接口中的方法,第二部分是映射文件中的语句,第三部分是日志文件中的语句。这里执行是顺利的。
这里我修改成了带注解的参数也会发生和下面一模一样的情况。
这里是会发生错误但是不报错的情况。
List<User> selByCondition(@Param("user") User user, @Param("index")int index, @Param("size")int size);
<select id="selByCondition" resultType="com.bjsxt.pojo.User">
<include refid="base_sql"/>
<where>
<if test="user.age!=null">
and age > #{user.age}
</if>
<if test="user.realname!=null and user.realname!=''">
<bind name="user.realname" value="'%'+user.realname+'%'"/>
and realname like #{user.realname}
</if>
</where>
limit #{index},#{size}
</select>
- [DEBUG] ==> Preparing: select id, username, password, realname, age, birthday, reg_time regTime from tb_user WHERE age > ? and realname like ? limit ?,?
- [DEBUG] ==> Parameters: null, %胡%(String), 0(Integer), 5(Integer)
- [DEBUG] <== Total: 0
这里也是分为三部分,第一部分是接口中的方法,第二部分是映射文件中的语句,第三部分是日志文件中的语句。
但是会丢失掉User中age的数据。下面是debug的状态
这里是日志文件查看。可以看到上面两次运行是不一样的地方,一次可以读取到,一次不可以读取到。
当我把bind标签去掉之后就可以顺利的读取到age的值了。
所以这里先暂时结合所学内容做猜测,加过注解之后的对象会被存放进map集合里面,bind标签里面的内容会从map里面将user取出来进行过加工之后在存放回去,所以会将之前的user覆盖掉。这里做了测试,不管bind标签在上还是在下都会使得age的值丢失,所以猜测if标签和bind标签之间存在一定的执行顺序,这个执行顺序不是按照位置来决定的。上面的user没有被覆盖掉是因为没有加注解,所以没有存放进入map集合里面。