目前的程序存在的问题
我们目前所写的程序,比如说是条件查询,在xml中的sql语句应该是select * from user where 属性=#{成员名}...
需要根据什么属性就需要把所有的属性都写上。当我们在测试时,如果没有使用其中的某一个属性作为筛选条件,也就是说我们认为那个属性可以是任意值,但是程序会认为把那个属性设置为null,查询时条件便会出错
解决方案:动态sql
第一种:多重条件判断select * from user where id=1 and username='tom' and password='tom'
出现的问题:判断条件有时存在有时不存在:使用if
注意:
- where标签相当sql:where 1=1
- if语句中的判断条件必须按照sql标准,用and连接
- test的属性值中的是实体类中的成员变量,不是表中的属性名
<select id="findByCondition" parameterType="user" resultType="user">
select * from user
<where>
<if test="id!=0">
and id=#{id}
</if>
<if test="userName!=null"> <!--必须是user类中的成员变量-->
and username=#{userName}
</if>
<if test="password!=null">
and password=#{password}
</if>
</where>
</select>
第二种:选择判断 or或者in select * from user where id=1 or id=2 or id=3;
select * from user where id in(1,2,3);
问题:id的值的范围极有可能改变,所以不能再sql配置文件中将sql语句写死
解决:在where标签中使用foreach标签,如下
- collection:如果参数是list,则属性值为list;如果参数是数组,则属性值为array
- open: select * from user where id in (1);
- close: select * from user where id in (1);
- item:遍历的值的名字
- separator:分隔符
<select id="findById" resultType="user" parameterType="List">
select * from user
<where>
<foreach collection="list" open="id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
<select id="findByIdArray" parameterType="int[]" resultType="user">
select * from user
<where>
<foreach collection="array" open="id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
sql抽取
为什么抽取:抽取出来后,如果我们要修改表名,只需要修改抽取出来的地方,不需要修改每一个更新、查询标签;如果要修改属性名同理
<sql id="sqlId">
select * from user
</sql>
<select id="findByCondition" parameterType="user" resultType="user">
<include refid="sqlId"></include>
<where>
<if test="id!=0">
and id=#{id}
</if>
<if test="userName!=null">
and username=#{userName}
</if>
<if test="password!=null">
and Password=#{password}
</if>
</where>
</select>