Mybatis动态SQL
随着用户的输入或外部条件的变化而变化的SQL语句,我们称为动态SQL。
@Mapper //在运行时,会自动生成该接口的实现类对象(代理对象),并且将该对象交给IOC容器管理
public interface EmpMapper {
public List<Emp> list(String name, Short gender, LocalDate begin,LocalDate end);
}
@SpringBootTest
class SpringbootMybatisCrudApplicationTests {
@Autowired
private EmpMapper empMapper;
@Test
public void selectList(){
// List<Emp> empList=empMapper.list("张",(short)1,LocalDate.of(2010,1,1),LocalDate.of(2020,1,1));
List<Emp> empList=empMapper.list("张",(short)1,null,null);
System.out.println(empList);
}
}
:用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL。
-
根据where的子标签判断条件是否有成立的,如果所有的条件都不成立,就不会生成where子句,如果有一个条件成立,会自动生成where子句;
-
会自动去除条件前面多余的and或者or
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.EmpMapper">
<!--id名称需要与mapper接口方法名一致-->
<!--resultType:指定查询结果封装成哪个Java类型-->
<select id="list" resultType="com.itheima.pojo.Emp">
select *
from emp
<where>
<if test="name != null">
name like concat('%', #{name}, '%')
</if>
<if test="gender != null">
and gender = #{gender}
</if>
<if test="begin != null and end != null">
and entrydate between #{begin} and #{end}
</if>
</where>
order by update_time desc
</select>
</mapper>
:动态地在行首插入set关键字,并会删除额外的逗号(用在update语句中)
sql片段
:定义可重用的SQL片段
:通过属性refid,指定包含的sql片段