4、动态sql

4、动态sql

4.1 动态sql-简介&环境搭建

  • 动态SQL是MyBatis强大特性之一。极大的简化我们拼装SQL的操作。
  • 动态SQL元素和使用 JSTL 或其他类似基于 XML 的文本处理器相似。
  • MyBatis采用功能强大的基于 OGNL 的表达式来简化操作。
    • if
    • choose (when, otherwise)
    • trim (where, set)
    • foreach

4.2 动态sql-if-判断&OGNL

DynamicSQLMapper.java

public interface DynamicSQLMapper {
	//携带了哪个字段查询条件就带上这个字段的值
	public List<Employee> getEmpsByConditionIf(Employee employee);
	
}

DynamicSQLMapper.xml

<mapper namespace="club.coderhome.c04.dynamicsql.DynamicSQLMapper">
	 
	 
	 <select id="getEmpsByConditionIf" resultType="club.coderhome.c01.helloworld.bean.Employee">
	 	select * from employee where
	 	
	 	<if test="id!=null">
	 		id=#{id}
	 	if>
	 	<if test="lastName!=null && lastName!=""">
	 		and last_name like #{lastName}
	 	if>
	 	<if test="email!=null and email.trim()!=""">
	 		and email=#{email}
	 	if> 
	 	
	 	<if test="gender==0 or gender==1">
	 	 	and gender=#{gender}
	 	if>
	 select>
mapper>

DynamicSQLMapperTest.java

public class DynamicSQLMapperTest {

	@Test
	public void testGetEmpsByConditionIf() throws IOException {
		SqlSessionFactory ssf = Tools.getSqlSessionFactory("c04/mybatis-config.xml");
		SqlSession session = ssf.openSession();
		
		try {
			DynamicSQLMapper dsm = session.getMapper(DynamicSQLMapper.class);
			Employee employee = new Employee(1, "jallen", null, null);
			System.out.println(dsm.getEmpsByConditionIf(employee));
			
			session.commit();
		} finally {
			session.close();
		}
	}

}

OGNL

OGNL官方文档

OGNL( Object Graph Navigation Language )对象图导航语言, 这是一种强大的表达式语言,通过它可以非常方便的来操作对象属性。 类似于我们的EL, SpEL等。

  • 访问对象属性: person.name
  • 调用方法: person.getName()
  • 调用静态属性/方法: @java.lang.Math@PI、@java.util.UUID@randomUUID()
  • 调用构造方法: new club.coderhome.Person(‘admin’).name
  • 运算符: +, -*, /, %
  • 逻辑运算符: in, not in, >, >=, <, <=, ==, !=

注意: xml中特殊符号如”,>,<等这些都需要使用转义字符

访问集合伪属性:

类型 伪属性 伪属性对应的 Java 方法
List、 Set、 Map size、 isEmpty List/Set/Map.size(),List/Set/Map.isEmpty()
List、 Set iterator List.iterator()、 Set.iterator()
Map keys、 values Map.keySet()、 Map.values()
Iterator next、 hasNext Iterator.next()、 Iterator.hasNext()

4.3 动态sql-where-查询条件

查询的时候如果某些条件没带可能sql拼装会有问题

  1. 给where后面加上1=1,以后的条件都and xxx。
  2. mybatis使用where标签来将所有的查询条件包括在内。mybatis就会将where标签中拼装的sql,多出来的and或者or去掉(where只会去掉第一个多出来的and或者or,但最后一个多出来的and或者or则不会去掉)。

DynamicSQLMapper.xml

<mapper namespace="club.coderhome.c04.dynamicsql.DynamicSQLMapper">

	 <select id="getEmpsByConditionIfWithWhere" resultType="club.coderhome.c01.helloworld.bean.Employee">
	 	select * from employee
	 	<where>
		 	<if test="id!=null">
		 		id=#{id}
		 	if>
		 	<if test="lastName!=null && lastName!=""">
		 		and last_name like #{lastName}
		 	if>
		 	<if test="email!=null and email.trim()!=""">
		 		and email=#{email}
		 	if> 
		 	
		 	<if test="gender==0 or gender==1">
		 	 	and gender=#{gender}
		 	if>
	 	where>
	 select>

 select>

DynamicSQLMapper.java

public interface DynamicSQLMapper {

	public List<Employee> getEmpsByConditionIfWithWhere(Employee employee);

DynamicSQLMapperTest.java

public class DynamicSQLMapperTest {

	@Test
	public void testGetEmpsByConditionIfWithWhere() throws IOException {
		SqlSessionFactory ssf = Tools.getSqlSessionFactory("c04/mybatis-config.xml");
		SqlSession session = ssf.openSession();
		
		try {
			DynamicSQLMapper dsm = session.getMapper(DynamicSQLMapper.class);
			Employee employee = new Employee(null, "jallen", null, null);
			System.out.println(dsm.getEmpsByConditionIfWithWhere(employee));
			
			session.commit();
		} finally {
			session.close();
		}
	}
	...

4.4 动态sql-trim-自定义字符串截取

后面多出的and或者or where标签不能解决

  • prefix=“”:前缀:trim标签体中是整个字符串拼串后的结果。
    • prefix给拼串后的整个字符串加一个前缀
  • prefixOverrides=“”:
    • 前缀覆盖: 去掉整个字符串前面多余的字符
  • suffix=“”:后缀
    • suffix给拼串后的整个字符串加一个后缀
  • suffixOverrides=“”
    • 后缀覆盖:去掉整个字符串后面多余的字符

DynamicSQLMapper.java

public interface DynamicSQLMapper {
	public List<Employee> getEmpsByConditionTrim(Employee employee);
	...

DynamicSQLMapper.xml

<mapper namespace="club.coderhome.c04.dynamicsql.DynamicSQLMapper">

	 
	 <select id="getEmpsByConditionTrim" resultType="club.coderhome.c01.helloworld.bean.Employee">
	 	select * from employee
	 	
	 	<trim prefix="where" suffixOverrides="and">
	 		<if test="id!=null">
		 		id=#{id} and
		 	if>
		 	<if test="lastName!=null && lastName!=""">
		 		last_name like #{lastName} and
		 	if>
		 	<if test="email!=null and email.trim()!=""">
		 		email=#{email} and
		 	if> 
		 	
		 	<if test="gender==0 or gender==1">
		 	 	gender=#{gender}
		 	if>
		 trim>
	 select>
	...

DynamicSQLMapperTest.java

public class DynamicSQLMapperTest {

	@Test
	public void testGetEmpsByConditionTrim() throws IOException {
		SqlSessionFactory ssf = Tools.getSqlSessionFactory("c04/mybatis-config.xml");
		SqlSession session = ssf.openSession();
		
		try {
			DynamicSQLMapper dsm = session.getMapper(DynamicSQLMapper.class);
			Employee employee = new Employee(1, "jallen", null, null);
			System.out.println(dsm.getEmpsByConditionTrim(employee));
			
			session.commit();
		} finally {
			session.close();
		}
	}
	...

4.5 动态sql-choose-分支选择

DynamicSQLMapper.java

public interface DynamicSQLMapper {
	
	public List<Employee> getEmpsByConditionChoose(Employee employee);
	...


DynamicSQLMapper.xml

<mapper namespace="club.coderhome.c04.dynamicsql.DynamicSQLMapper">

	 
	 <select id="getEmpsByConditionChoose" resultType="club.coderhome.c01.helloworld.bean.Employee">
	 	select * from employee 
	 	<where>
	 		
	 		<choose>
	 			<when test="id!=null">
	 				id=#{id}
	 			when>
	 			<when test="lastName!=null">
	 				last_name like #{lastName}
	 			when>
	 			<when test="email!=null">
	 				email = #{email}
	 			when>
	 			<otherwise>
	 				gender = 0
	 			otherwise>
	 		choose>
	 	where>
	 select>


DynamicSQLMapperTest.java

public class DynamicSQLMapperTest {

	@Test
	public void testGetEmpsByConditionChoose() throws IOException {
		SqlSessionFactory ssf = Tools.getSqlSessionFactory("c04/mybatis-config.xml");
		SqlSession session = ssf.openSession();
		
		try {
			DynamicSQLMapper dsm = session.getMapper(DynamicSQLMapper.class);
			Employee employee = new Employee(1, "jallen", null, null);
			System.out.println(dsm.getEmpsByConditionChoose(employee));
			
			session.commit();
		} finally {
			session.close();
		}
	}

4.6 动态sql-set-与if结合的动态更新

DynamicSQLMapper.java

public interface DynamicSQLMapper {
	
	public void updateEmp(Employee employee);


DynamicSQLMapper.xml

<mapper namespace="club.coderhome.c04.dynamicsql.DynamicSQLMapper">

	 
	 <update id="updateEmp">
	 	
	 	update employee 
		<set>
			<if test="lastName!=null">
				last_name=#{lastName},
			if>
			<if test="email!=null">
				email=#{email},
			if>
			<if test="gender!=null">
				gender=#{gender}
			if>
		set>
		where id=#{id} 
	
	 update>

DynamicSQLMapperTest.java

public class DynamicSQLMapperTest {

	@Test
	public void testUpdateEmp() throws IOException {
		SqlSessionFactory ssf = Tools.getSqlSessionFactory("c04/mybatis-config.xml");
		SqlSession session = ssf.openSession();
		
		try {
			DynamicSQLMapper dsm = session.getMapper(DynamicSQLMapper.class);
			
			Employee employee = new Employee(1, "jallen2", null, null);
			dsm.updateEmp(employee);
			
			session.commit();
		} finally {
			session.close();
		}
	}

4.7 动态sql-foreach-遍历集合

  • collection:指定要遍历的集合:
    • list类型的参数会特殊处理封装在map中,map的key就叫list
  • item:将当前遍历出的元素赋值给指定的变量
  • separator:每个元素之间的分隔符
  • open:遍历出所有结果拼接一个开始的字符
  • close:遍历出所有结果拼接一个结束的字符
  • index:索引。遍历list的时候是index就是索引,item就是当前值
    • 遍历map的时候index表示的就是map的key,item就是map的值
  • #{变量名}就能取出变量的值也就是当前遍历出的元素

DynamicSQLMapper.java

public interface DynamicSQLMapper {
	
	public List<Employee> getEmpsByConditionForeach(@Param("ids")List<Integer> ids);

DynamicSQLMapper.xml

<mapper namespace="club.coderhome.c04.dynamicsql.DynamicSQLMapper">

	 <!--public List<Employee> getEmpsByConditionForeach(List<Integer> ids);  -->
	 <select id="getEmpsByConditionForeach" resultType="club.coderhome.c01.helloworld.bean.Employee">
	 	select * from employee
	 	<foreach collection="ids" item="item_id" separator=","
	 		open="where id in(" close=")">
	 		#{item_id}
	 	</foreach>
	 </select>

DynamicSQLMapperTest.java

public class DynamicSQLMapperTest {
	
	@Test
	public void testGetEmpsByConditionForeach() throws IOException {
		SqlSessionFactory ssf = Tools.getSqlSessionFactory("c04/mybatis-config.xml");
		SqlSession session = ssf.openSession();
		try {
			DynamicSQLMapper dsm = session.getMapper(DynamicSQLMapper.class);
			
			System.out.println(dsm.getEmpsByConditionForeach(Arrays.asList(1,2,3)));
			
			session.commit();
		} finally {
			session.close();
		}
	}

4.8 动态sql-foreach-mysql下foreach批量插入的两种方式

DynamicSQLMapper.java

public interface DynamicSQLMapper {
	
	public void addEmps(@Param("emps")List<Employee> emps);
	
	public void addEmps2(@Param("emps")List<Employee> emps);
	

DynamicSQLMapper.xml

<mapper namespace="club.coderhome.c04.dynamicsql.DynamicSQLMapper">

	 
	 
	 
	<insert id="addEmps">
	 	insert into employee(last_name,email,gender,department_id) 
		values
		<foreach collection="emps" item="emp" separator=",">
			(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.department.id})
		foreach>
	 insert>
	 
	 
	 <insert id="addEmps2">
	 	<foreach collection="emps" item="emp" separator=";">
	 		insert into employee(last_name,email,gender,department_id)
	 		values(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.department.id})
	 	foreach>
	 insert>

注意,MySQL数据库连接属性allowMultiQueries=true,才能批量删除,修改数据。(在连接MySQL的URL后添加参数)。


DynamicSQLMapperTest.java

public class DynamicSQLMapperTest {
	
	@Test
	public void testAddEmps2() throws IOException {
		SqlSessionFactory ssf = Tools.getSqlSessionFactory("c04/mybatis-config.xml");
		SqlSession session = ssf.openSession();
		try {
			DynamicSQLMapper dsm = session.getMapper(DynamicSQLMapper.class);
			
			dsm.addEmps2(Arrays.asList(new Employee(null, "abc", null, null),
					new Employee(null, "cba",null, null)));
			
			session.commit();
		} finally {
			session.close();
		}
	}
	
	@Test
	public void testAddEmps() throws IOException {
		SqlSessionFactory ssf = Tools.getSqlSessionFactory("c04/mybatis-config.xml");
		SqlSession session = ssf.openSession();
		try {
			DynamicSQLMapper dsm = session.getMapper(DynamicSQLMapper.class);
			dsm.addEmps(Arrays.asList(new Employee(null, "abc", null, null),
					new Employee(null, "cba",null, null)));
			session.commit();
		} finally {
			session.close();
		}
	}

4.9 动态sql-foreach-oracle下批量插入的两种方式

Oracle数据库批量保存:

  • Oracle不支持values(),(),()

Oracle支持的批量方式:

  1. 多个insert放在begin - end里面
  2. 利用中间表
# 多个insert放在begin - end里面
begin
    insert into employees(employee_id,last_name,email) 
    values(employees_seq.nextval,'test_001','[email protected]');
    insert into employees(employee_id,last_name,email) 
    values(employees_seq.nextval,'test_002','[email protected]');
end;

# 利用中间表
insert into employees(employee_id,last_name,email)
   select employees_seq.nextval,lastName,email from(
          select 'test_a_01' lastName,'test_a_e01' email from dual
          union
          select 'test_a_02' lastName,'test_a_e02' email from dual
          union
          select 'test_a_03' lastName,'test_a_e03' email from dual
   );

4.10 动态sql-foreach-oracle下foreach批量保存两种方式

<insert id="addEmps" databaseId="oracle">
	
	
	
	
	insert into employees(employee_id,last_name,email)
	<foreach collection="emps" item="emp" separator="union"
		open="select employees_seq.nextval,lastName,email from("
		close=")">
		select #{emp.lastName} lastName,#{emp.email} email from dual
	foreach>
insert>

4.11 动态sql-内置参数 _parameter & _databaseId

不只是方法传递过来的参数可以被用来判断,

mybatis默认还有两个内置参数

  1. _parameter

    :代表整个参数

    • 单个参数:_parameter就是这个参数
    • 多个参数:参数会被封装为一个map;_parameter就是代表这个map
  2. _databaseId

    :如果配置了databaseIdProvider标签。

    • _databaseId就是代表当前数据库的别名oracle

<select id="getEmpsTestInnerParameter" resultType="club.coderhome.c01.helloworld.bean.Employee">

	<if test="_databaseId=='mysql'">
		select * from tbl_employee
		<if test="_parameter!=null">
			where last_name like #{_parameter.lastName}
		if>
	if>

	<if test="_databaseId=='oracle'">
		select * from employees
		<if test="_parameter!=null">
			where last_name like #{_parameter.lastName}
		if>
	if>
select>

4.12 动态sql-bind-绑定


<select id="getEmpsTestInnerParameter" resultType="com.atguigu.mybatis.bean.Employee">

		
		<bind name="lastName" value="'%'+lastName+'%'"/>

		<if test="_databaseId=='mysql'">
			select * from tbl_employee
			<if test="_parameter!=null">
				where last_name like #{lastName}
			if>
		if>
		<if test="_databaseId=='oracle'">
			select * from employees
			<if test="_parameter!=null">
				where last_name like #{_parameter.lastName}
			if>
		if>
select>

4.13 动态sql-sql-抽取可重用的sql片段

抽取可重用的sql片段。方便后面引用:

  1. sql抽取:经常将要查询的列名,或者插入用的列名抽取出来方便引用
  2. include来引用已经抽取的sql:
  3. include还可以自定义一些property,sql标签内部就能使用自定义的属性
    • include-property:取值的正确方式${prop},
    • 不能使用#{},而使用${}
<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password </sql>

<select id="selectUsers" resultType="map">
	select
		<include refid="userColumns"><property name="alias" value="t1"/></include>,
		<include refid="userColumns"><property name="alias" value="t2"/></include>
	from some_table t1
		cross join some_table t2
</select>

<sql id="insertColumn">
	<if test="_databaseId=='oracle'">
		employee_id,last_name,email
	</if>
	<if test="_databaseId=='mysql'">
		last_name,email,gender,d_id
	</if>
</sql>

...

<insert id="addEmps">
	insert into tbl_employee(
		<include refid="insertColumn"></include><!-- 使用地方 -->
	) 
	values
	<foreach collection="emps" item="emp" separator=",">
		(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
	</foreach>
 </insert>

你可能感兴趣的:(mybatis,sql,mybatis,java)