Mybatis动态SQL

1.动态sql语句概述

Mybatis 的映射文件中,前面我们的 SQL 都是比较简单的,有些时候业务逻辑复杂时,我们的

SQL是动态变化的,此时在前面的学习中我们的 SQL 就不能满足要求了。

2.if标签的使用

根据实体类的不同取值,使用不同的 SQL语句来进行查询

<where>:条件标签,如果有动态条件,则使用该标签代替where关键字

<if>:条件判断标签

java 复制代码
<if test="条件判断">
	拼接的查询条件
</if>

例:多条件查询

StudentMapper.xml:

XML 复制代码
 <select id="selectCondition" resultType="student" parameterType="student">
        select * from student
        <where>
            <if test="id != null">
                id = #{id}
            </if>
            <if test="name != null">
               AND name = #{name}
            </if>
            <if test="id != null">
                AND age = #{age}
            </if>
        </where>
    </select>

Mapper接口:

java 复制代码
//多条件查询
public abstract List<Student> selectCondition(Student stu);

测试类:

java 复制代码
package Mybatis2;

import Mybatis2.mapper.StudentMapper;
import mybatis1.bean.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;


public class test1 {
    @Test
    public void selectCondition() throws Exception {
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //获取StudentMapper接口的实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        Student stu = new Student();
        stu.setId(2);
        stu.setName("李四");
        stu.setAge(24);
        //调用实现类的方法,接收结果
        List<Student> list = mapper.selectCondition(stu);

        //处理结果
        for (Student student : list) {
            System.out.println(student);
        }

        sqlSession.close();
        is.close();
    }
}

3.foreach标签的使用

<foreach>:循环遍历标签。适用于多个参数或者的关系

XML 复制代码
<foreach collection="" open="" close="" item="" separator="">
	获取参数
</foreach>

属性:

collection:参数容器类型,(list-集合,array-数组)

open:开始的SQL语句

close:结束的SQL语句

item:参数变量名

separator:分隔符

增加StudentMapper.xml:

XML 复制代码
<select id="selectByIds" resultType="student" parameterType="list">
    <include refid="select"/>
    <where>
        <foreach collection="list" open="id IN (" close=")" item="id" separator=",">
            #{id}
        </foreach>
    </where>
</select>

Mapper接口:

java 复制代码
//根据多个id查询
    public abstract List<Student> selectByIds(List<Integer> sids);

测试类:

java 复制代码
@Test
    public void selectByIds() throws Exception{
        //1.加载核心配置文件
        InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
        //2.获取SqlSession工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通过工厂对象获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.获取StudentMapper接口的实现类对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5.调用实现类的方法,接收结果
        List<Integer> sids = new ArrayList<>();
        sids.add(1);
        sids.add(2);
        List<Student> list = mapper.selectByIds(sids);
        for(Student student : list){
            System.out.println(student);
        }
        sqlSession.close();
        is.close();
    }

4.SQL片段的抽取

我们可以将一些重复性的SQL语句进行抽取,以达到复用的效果

<sql>:抽取SQL语句的标签

<sql id="片段唯一标识">抽取的SQL语句</sql>

<include>:引入SQL片段标签

<include refid="片段唯一标识" />

XML 复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD约束-->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
    mapper:核心根标签
    namespace属性:名称空间
-->
<mapper namespace="Mybatis2.mapper.StudentMapper">
    
    <sql id="select">SELECT * FROM student</sql>
    <!--select:查询功能的标签
        id属性:唯一标识
        resultType属性:指定结果映射对象类型
        parameterType属性:指定参数映射对象类型-->
    <select id="selectAll" resultType="Student">
        <include refid="select"/>
    </select>
    <select id="selectById" resultType="Student" parameterType="java.lang.Integer">
        <include refid="select"/> WHERE id = #{id}
    </select>
    <insert id="insert" parameterType="Student">
        INSERT INTO student VALUES (#{id},#{name},#{age})
    </insert>

    <delete id="delete" parameterType="Student">
        DELETE FROM student WHERE id = #{id}
    </delete>

    <select id="selectCondition" resultType="student" parameterType="student">
        <include refid="select"/>
        <where>
            <if test="id != null">
                id = #{id}
            </if>
            <if test="name != null">
               AND name = #{name}
            </if>
            <if test="id != null">
                AND age = #{age}
            </if>
        </where>
    </select>
    <select id="selectByIds" resultType="student" parameterType="list">
        <include refid="select"/>
        <where>
            <foreach collection="list" open="id IN (" close=")" item="id" separator=",">
                #{id}
            </foreach>
        </where>
    </select>

</mapper>
相关推荐
IT乐手3 分钟前
Java 实现异步转同步的方法
java
杨杨杨大侠3 分钟前
附录 1:🚀 Maven Central 发布完整指南:从零到成功部署
java·github·maven
渣哥25 分钟前
Java HashMap 扩容机制详解:触发条件与实现原理
java
赵星星52025 分钟前
Spring Bean线程安全陷阱:90%程序员都会踩的坑,你中招了吗?
java
得物技术1 小时前
0基础带你精通Java对象序列化--以Hessian为例|得物技术
java·后端·编程语言
时序数据说1 小时前
物联网时序数据管理的利器:为何IoTDB备受青睐?
大数据·数据库·物联网·时序数据库·iotdb
橘子在努力1 小时前
【橘子SpringCloud】OpenFegin源码分析
java·spring boot·spring·spring cloud
我是廖志伟1 小时前
JVM新生代Eden区域深度解析
java·jvm·memory management
十八旬1 小时前
苍穹外卖项目实战(day7-2)-购物车操作功能完善-记录实战教程、问题的解决方法以及完整代码
java·开发语言·windows·spring boot·mysql
BIGSHU09232 小时前
java多线程场景3-并发处理和异步请求
java·开发语言·python