JavaEE——Mybatis(7)--动态SQL if choose trim foreach

<!--
if:判断
choose (when, otherwise):分支选择;带了break的swtich-case
如果带了id就用id查,如果带了lastName就用lastName查;只会进入其中一个
trim 字符串截取(where(封装查询条件), set(封装修改条件))
foreach 遍历集合
-->
<!-- 查询学生,要求,携带了哪个字段查询条件就带上这个字段的值 -->
<!-- public List<Students> getStuByConditionIf(Students student);-->

<!--public List<Students> getStuByConditionIf(Students student);-->
    <select id="getStuByConditionIf" resultType="com.person.Students">
        SELECT * FROM student
        WHERE
        <!-- test:判断表达式(OGNL)
		 	OGNL参照PPT或者官方文档。
		 	  	 c:if  test
		 	从参数中取值进行判断
		 	-->
        <if test="id!=null">
            id=#{id}
        </if>
        <if test="name!=null and name!=""">
            AND name LIKE #{name}
        </if>
       <!-- <if test="sex!=null && sex.trim()!=''">-->
        <if test="sex == "girl" or sex == "boy"">
            AND sex=#{sex}
        </if>
        <if test="age!=null">
            AND age=#{age}
        </if>
    </select>

  注:查询的时候如果某些条件没带可能sql拼装会有问题  如第一个没有id,则后序会在where后面直接接上and,不合法的SQL语句

 解决方法:1、给where后面加上1=1,以后的条件都and xxx.

     2、mybatis使用where标签来将所有的查询条件包括在内。(只需要将SQL语句中的where换成<where> 中间写if语句即可 </where> )mybatis就会将where标签中拼装的sql,多出来的and或者or去掉

    注意:where只会去掉第一个多出来的and或者or。

     3、trim 字符串截取(where(封装查询条件), set(封装修改条件))

<!--public List<Students> getStuByConditionTrim(Students student);-->
    <select id="getStuByConditionTrim" resultType="com.person.Students">
        SELECT * FROM student
        <trim prefix="where" suffixOverrides="and">
            <if test="id!=null">
                id=#{id} AND
            </if>
            <if test="name!=null && name!=""">
                name LIKE #{name} AND
            </if>
            <if test="sex=="girl" or sex=="boy"">
                sex=#{sex} AND
            </if>
            <if test="age!=null">
                age=#{age}
            </if>
        </trim>
    </select>

  

 trim标签后面多出的and或者or where标签不能解决
  prefix="":前缀:trim标签体中是整个字符串拼串 后的结果。
    prefix给拼串后的整个字符串一个前缀
  prefixOverrides="":
    前缀覆盖: 去掉整个字符串前面多余的字符
  suffix="":后缀
    suffix给拼串后的整个字符串一个后缀
  suffixOverrides=""
    后缀覆盖:去掉整个字符串后面多余的字符

choose标签:只会进入其中一个

<!--public List<Students> getStuByConditionChoose(Students student);-->
    <select id="getStuByConditionChoose" resultType="com.person.Students">
        SELECT * FROM student
       <where>
            <choose>
                <when test="id!=null">
                    id=#{id}
                </when>
                <when test="name!=null && name!=""">
                    name LIKE #{name}
                </when>
                <when test="sex=="girl" or sex=="boy"">
                    sex=#{sex}
                </when>
                <when test="age!=null">
                    age=#{age}
                </when>
                <otherwise>
                    1=1
                </otherwise>
            </choose>

       </where>
    </select>

  set标签  封装修改条件

<!--public void updateEmp(Employee employee);  -->
	 <update id="updateEmp">
	 	<!-- Set标签的使用 -->
	 	update tbl_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} 

  

forEach标签

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

批量查询

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

  批量保存

<!--批量保存-->
    <!--public void insertStu(@Param("students")List<Students> students);-->
    <insert id="insertStu">
        INSERT INTO student(name, sex, age, grade_id) VALUES
        <foreach collection="students" item="stu" separator=",">
            (#{stu.name},#{stu.sex},#{stu.age},#{stu.grade.id})
        </foreach>
    </insert>

  测试代码  注意这里的openSession.commit()必须要写

    @Test
    public void test6() throws IOException {
        String resource = "conf/com/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession openSession = sqlSessionFactory.openSession();

        try{
            StudentMapperDynamicSQL mapper = openSession.getMapper( StudentMapperDynamicSQL.class );

            List<Students> students = new ArrayList<>();
            students.add(new Students(null, "22", "boy", null, new Grade(1)));
            students.add(new Students(null, "ww", "boy", null, new Grade(2)));
            mapper.insertStu(students);
            openSession.commit();
        }finally{

            openSession.close();
        }
    }

  另外一种批量保存的方法

<!-- 这种方式需要数据库连接属性allowMultiQueries=true;
	 	这种分号分隔多个sql可以用于其他的批量操作(删除,修改) -->
	 <!-- <insert id="addEmps">
	 	<foreach collection="emps" item="emp" separator=";">
	 		insert into tbl_employee(last_name,email,gender,d_id)
	 		values(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
	 	</foreach>
	 </insert> -->

 

Oracle下的两种保存方式

<!-- Oracle数据库批量保存: 
	 	Oracle不支持values(),(),()
	 	Oracle支持的批量方式
	 	1、多个insert放在begin - end里面
	 		begin
			    insert into employees(employee_id,last_name,email) 
			    values(employees_seq.nextval,'test_001','test_001@atguigu.com');
			    insert into employees(employee_id,last_name,email) 
			    values(employees_seq.nextval,'test_002','test_002@atguigu.com');
			end;
		2、利用中间表:
			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
		       )	
	 -->
	 <insert id="addEmps" databaseId="oracle">
	 	<!-- oracle第一种批量方式 -->
	 	<!-- <foreach collection="emps" item="emp" open="begin" close="end;">
	 		insert into employees(employee_id,last_name,email) 
			    values(employees_seq.nextval,#{emp.lastName},#{emp.email});
	 	</foreach> -->
	 	
	 	<!-- oracle第二种批量方式  -->
	 	insert into employees(
	 		<!-- 引用外部定义的sql -->
	 		<include refid="insertColumn">
	 			<property name="testColomn" value="abc"/>
	 		</include>
	 	)
	 			<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>

  

sql标签抽取可重用的sql片段。方便后面引用
1、sql抽取:经常将要查询的列名,或者插入用的列名抽取出来方便引用
2、include来引用已经抽取的sql:
3、include还可以自定义一些property,sql标签内部就能使用自定义的属性
include-property:取值的正确方式${prop},
#{不能使用这种方式}
-->

<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默认还有两个内置参数:
_parameter:代表整个参数
  单个参数:_parameter就是这个参数
  多个参数:参数会被封装为一个map;_parameter就是代表这个map

_databaseId:如果配置了databaseIdProvider标签。
_databaseId就是代表当前数据库的别名oracle

<!--public List<Employee> getEmpsTestInnerParameter(Employee employee);  -->
	  <select id="getEmpsTestInnerParameter" resultType="com.atguigu.mybatis.bean.Employee">
	  		<!-- bind:可以将OGNL表达式的值绑定到一个变量中,方便后来引用这个变量的值 -->
	  		<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>

  

原文地址:https://www.cnblogs.com/SkyeAngel/p/8259097.html