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>
相关推荐
Z字小熊饼干爱吃保安几秒前
面试技术问题总结一
数据库·面试·职场和发展
风象南1 分钟前
SpringBoot应用开机自启动与进程守护配置
java·spring boot·后端
字节卷动11 分钟前
【牛客刷题】活动安排
java·算法·牛客
极限实验室15 分钟前
一键启动:使用 start-local 脚本轻松管理 INFINI Console 与 Easysearch 本地环境
数据库·docker
fouryears_2341719 分钟前
Spring核心原理的快速入门:快速了解IoC与DI
java·后端·spring
没有口袋啦19 分钟前
《数据库》第一次作业:MySQL数据库账户及授权
数据库·mysql
顽疲30 分钟前
从零用java实现 小红书 springboot vue uniapp(13)模仿抖音视频切换
java·vue.js·spring boot
星辰离彬1 小时前
Java 与 MySQL 性能优化:MySQL连接池参数优化与性能提升
java·服务器·数据库·后端·mysql·性能优化
半桔1 小时前
【Linux手册】从接口到管理:Linux文件系统的核心操作指南
android·java·linux·开发语言·面试·系统架构
nightunderblackcat1 小时前
新手向:实现ATM模拟系统
java·开发语言·spring boot·spring cloud·tomcat·maven·intellij-idea