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>
相关推荐
胡八一1 分钟前
SQLite / LiteDB 单文件数据库为何“清空表后仍占几 GB”?——原理解析与空间回收实战
jvm·数据库·sqlite
都叫我大帅哥1 小时前
深入浅出 Resilience4j:Java 微服务的“免疫系统”实战指南
java·spring cloud
2401_831501731 小时前
Linux之Zabbix分布式监控篇(二)
数据库·分布式·zabbix
秋林辉2 小时前
Jfinal+SQLite处理 sqlite数据库执行FIND_IN_SET报错
jvm·数据库·sqlite
Cao_Shixin攻城狮3 小时前
Flutter运行Android项目时显示java版本不兼容(Unsupported class file major version 65)的处理
android·java·flutter
巴里巴气6 小时前
MongoDB复杂查询 聚合框架
数据库·mongodb
Dcs6 小时前
还在用 Arrays.hashCode?Java 自己也能写出更快的版本!
java
fouryears_234178 小时前
Spring,Spring Boot 和 Spring MVC 的关系以及区别
java·spring boot·spring·mvc
阿葱(聪)8 小时前
java 在k8s中的部署流程
java·开发语言·docker·kubernetes
scheduleTTe8 小时前
SQL增查
数据库·sql