文章目录
- 1.< if >元素
- 2.<where>
- 3.<choose>,<when>,<otherwise>元素
- 4.<trim>元素
- 5.<set>元素
- 6.<foreach>元素
- 6.1 添加批量数据
- 6.2 批量删除数据
- 7.小结
一、< if >元素
在MyBatis中,< if > 是最常用的判断语句,它类似于Java中的if语句,主要用于实现某些简单的条件选择。
//查询动态SQL语句
<select id="getSuppliersAll" parameterType="Supplier" resultType="pojo.Supplier">
select * from t_supplier
<if test="supCode!=null">
and supCode=#{supCode}
</if>
<if test="supName!=null">
and supName=#{supName}
</if>
<if test="supContact!=null">
and supContact=#{supContact}
</if>
</select>
测试方法:
//动态SQL:查询
@Test
public void getSupplierAll() throws Exception {
val sqlSession = MybatisUtil.openSession();
Supplier supplier=new Supplier();
supplier.setSupCode("GZ_GYS0022");
supplier.setSupName("罗狗宠物有限公司");
supplier.setSupContact("罗狗");
List<Supplier> supplierList=sqlSession.getMapper(SupperMapper.class).getSuppliersAll(supplier);
sqlSession.commit();
System.out.println(supplierList);
}
测试结果如下:
同时在为传递任何参数时,程序会将数据表中的所有数据查出
二、<where>
使用if语句查询我们注意到select * from t_emp where 1=1
在语句中要添加where 1=1
这是为了保证至少有条件成立,不至于程序报错,但是MyBatis的开发者设计了更好的方法,就是把< where >也作为元素,动态添加where,使用如下
<select id="getSuppliersAll" parameterType="Supplier" resultType="pojo.Supplier">
select * from t_supplier
<where>
<if test="supCode!=null">
and supCode=#{supCode}
</if>
<if test="supName!=null">
and supName=#{supName}
</if>
<if test="supContact!=null">
and supContact=#{supContact}
</if>
</where>
</select>
这样就避免了那个设定
三、 < choose >,< when >,< otherwise >元素
在使用< if >元素时,只要test属性中的表达式为true,就会执行元素中的条件语句,但是在实际应用中,有时只需要从多个选项中选择一个去执行。在这种场景下,使用< if > 元素进行处理是非常不合理的。如果使用的是Java语言,这种情况显然更适合switch语句来处理,那么MyBatis中有没有类似的语句呢?当然是有的。针对上面的情况,MyBatsi可以用< choose >,< when >,< otherwise >元素组合去实现上面的情况。
<select id="getEmpByChoose" resultType="Emp">
select * from t_emp
<where>
<choose>
<when test="empName != null and empName != ''">
emp_name = #{empName}
</when>
<when test="age != null and age != ''">
age = #{age}
</when>
<when test="gender != null and gender != ''">
gender = #{gender}
</when>
</choose>
</where>
</select>
测试语句:
public void testGetEmpByChoose(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
Emp emp = new Emp(null, "张三", 21, "");
List<Emp> list = mapper.getEmpByChoose(emp);
list.forEach(System.out::println);
}
结果如下:
这是因为当条件满足其中一项,在这个案例中就是满足了名字,那么后面的就不会再去匹配啦,所以这里的查询是按照名字也就是张三来进行的。
四、<trim>元素
trim元素用于自定义拼接SQL语句,与where类似
< where >版
<select id="getSuppliersAll" parameterType="Supplier" resultType="pojo.Supplier">
select * from t_supplier
<where>
<if test="supCode!=null">
and supCode=#{supCode}
</if>
<if test="supName!=null">
and supName=#{supName}
</if>
<if test="supContact!=null">
and supContact=#{supContact}
</if>
</where>
</select>
<trim>版
<select id="getSuppliersAll" parameterType="Supplier" resultType="pojo.Supplier">
select * from t_supplier
<trim prefix="where" prefixOverrides="and|or">
<if test="supCode!=null">
and supCode=#{supCode}
</if>
<if test="supName!=null">
and supName=#{supName}
</if>
<if test="supContact!=null">
and supContact=#{supContact}
</if>
</trim>
</select>
trim用于去掉或添加标签中的内容
常用属性:
prefix:在trim标签中的内容的前面添加某些内容
prefixOverrides:在trim标签中的内容的前面去掉某些内容
suffix:在trim标签中的内容的后面添加某些内容
suffixOverrides:在trim标签中的内容的后面去掉某些内容
五、<set>元素
在更新表中字段时,根据条件进行判断,从而实现部分更改,而不是更新所有字段,提高开发效率
<update id="updateSupplier" parameterType="pojo.Supplier">
update t_supplier
<trim prefixOverrides="," suffix="where">
<set>
<if test="supCode!=''">
supCode=#{supCode},
</if>
<if test="supName!=''">
supName=#{supName},
</if>
<if test="supContact!=''">
supContact=#{supContact}
</if>
</set>
</trim>
id=#{id}
</update>
其中的< if >元素用于判断相应的字段是否传入值,如果传入的字段非空,就将此字段进行动态SQL组转;并更新此字段,否则此字段不更新。
注意:在映射文件中使用 < set > 和 < if >元素组合纪念性update语句动态SQL组转时,如果< set >元素内包含的内容都为空,则会出现SQL语法错误。所以在使用< set > 元素进行字段信息更新时,要确保传入的更新字段都不能为空。
六、< foreach >元素
用于SQL语句执行批量操作
1、collection: 需做foreach(遍历)的对象,作为入参时,list、array对象时,collection属性值分别默认用"list"、"array"代替,Map对象没有默认的属性值。但是,在作为入参时可以使用@Param(“keyName”)注解来设置自定义collection属性值,设置keyName后,list、array会失效;
2、item: 集合元素迭代时的别名称,该参数为必选项;
3、index: 在list、array中,index为元素的序号索引。但是在Map中,index为遍历元素的key值,该参数为可选项;
4、open: 遍历集合时的开始符号,通常与close=")"搭配使用。使用场景IN(),values()时,该参数为可选项;
5、separator: 元素之间的分隔符,类比在IN()的时候,separator=“,”,最终所有遍历的元素将会以设定的(,)逗号符号隔开,该参数为可选项;
6、close: 遍历集合时的结束符号,通常与open="("搭配使用,该参数为可选项;
6.1 添加批量数据
<insert id="addSupplier" parameterType="java.util.List">
insert into t_supplier(supCode,supName,supContact) values
<foreach collection="supplier" item="supplier"
separator=",">
(#{supplier.supCode},#{supplier.supName},#{supplier.supContact})
</foreach>
</insert>
测试方法:
//动态SQL:新增
@Test
public void addSupplier() throws IOException {
val session = getSqlSession();
SqlSession sqlSession= session;
List<Supplier> supplierList=new ArrayList<>();
Supplier supplier=new Supplier();
supplier.setSupCode("GZ_DF154");
supplier.setSupName("罗狗宠物有限公司");
supplier.setSupContact("罗狗");
Supplier supplier1=new Supplier();
supplier1.setSupCode("GZ_DF164");
supplier1.setSupName("狗志宠物有限公司");
supplier1.setSupContact("狗志");
supplierList.add(supplier);
supplierList.add(supplier1);
Integer count=sqlSession.getMapper(mapper.SupperMapper.class).addSupplier(supplierList);
sqlSession.commit();
System.out.println(count);
}
执行结果:
6.2 批量删除数据
<delete id="delSupplier" parameterType="java.util.List">
delete from t_supplier where id in
<foreach collection="delSupplier" item="id"
open="(" separator="," close=")">
#{id}
</foreach>
</delete>
测试方法:
//动态SQL:删除
@Test
public void delSupplier() throws IOException {
val session = getSqlSession();
SqlSession sqlSession= session;
List<Integer> Supplierlist=new ArrayList<>();
Supplierlist.add(18);
Supplierlist.add(19);
Integer count=sqlSession.getMapper(mapper.SupperMapper.class).delSupplier(Supplierlist);
sqlSession.commit();
System.out.println(count);
}
执行结果:
也可以这么拼接SQL语句
<delete id="deleteByEmpIds">
delete from t_emp where
<foreach collection="empIds" item="empId" separator="or" >
emp_id=#{empId}
</foreach>
</delete>
七、小结
动态SQL可以帮开发者灵巧的实现很多特殊条件的SQL语句,比如if元素是最常用的,同时要灵活使用sql语句来完成嵌套查询,要根据项目要求选取合适的元素来实现开发。