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>
相关推荐
2402_8575893624 分钟前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
吾爱星辰1 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
vvvae12342 小时前
分布式数据库
数据库
哎呦没2 小时前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
雪域迷影2 小时前
PostgreSQL Docker Error – 5432: 地址已被占用
数据库·docker·postgresql
编程、小哥哥2 小时前
netty之Netty与SpringBoot整合
java·spring boot·spring
bug菌¹3 小时前
滚雪球学Oracle[4.2讲]:PL/SQL基础语法
数据库·oracle
逸巽散人3 小时前
SQL基础教程
数据库·sql·oracle
IT学长编程3 小时前
计算机毕业设计 玩具租赁系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·计算机毕业设计选题·玩具租赁系统
莹雨潇潇3 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器