【SSM框架】动态SQL

简介: 1.if2.where3.trim4.choose、when、otherwise 5.foreach1.批量添加数据2.批量删除数据6.SQL片段

表:



实体类:

public class Emp {
    private Integer empId;
    private String empName;
    private Integer age;
    private String gender;
    public Emp() {
    }
    public Emp(Integer empId, String empName, Integer age, String gender) {
        this.empId = empId;
        this.empName = empName;
        this.age = age;
        this.gender = gender;
    }
    public Integer getEmpId() {
        return empId;
    }
    public void setEmpId(Integer empId) {
        this.empId = empId;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    @Override
    public String toString() {
        return "Emp{" +
                "empId=" + empId +
                ", empName='" + empName + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
    }
}

1.if


if 标签可通过 test 属性的表达式进行判断,若表达式的结果为 true ,则标签中的内容会执行;反之标签中的内容不会执行

    <select id="getEmpByyCondition" resultType="com.atguigu.mybatis.pojo.Emp">
        select * from t_emp where 1=1
        <if test="empName!=null and empName!=''">
            and emp_name=#{empName}
        </if>
        <if test="age!=null and age!=''">
            and age=#{age}
        </if>
        <if test="gender!=null and gender!=''">
            and gender=#{gender}
        </if>
    </select>

测试:

    public void test6(){
        SqlSessionUtils sqlSessionUtils = new SqlSessionUtils();
        SqlSession sqlSession = sqlSessionUtils.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        Emp emp = new Emp(null,"张三",null,null);
        List<Emp> list = mapper.getEmpByyCondition(emp);
        System.out.println(list);
    }


2.where


where和if一般结合使用:


若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字


若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的and去掉


注意:where标签不能去掉条件最后多余的and

    <select id="getEmpByyCondition" resultType="com.atguigu.mybatis.pojo.Emp">
        select * from t_emp
        <where>
            <if test="empName!=null and empName!=''">
                and emp_name=#{empName}
            </if>
            <if test="age!=null and age!=''">
                and age=#{age}
            </if>
            <if test="gender!=null and gender!=''">
                and gender=#{gender}
            </if>
        </where>
    </select>

1.若where标签中的if条件都不满足,则where标签没有任何功能

    public void test6(){
        SqlSessionUtils sqlSessionUtils = new SqlSessionUtils();
        SqlSession sqlSession = sqlSessionUtils.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        Emp emp = new Emp(null,null,null,null);
        List<Emp> list = mapper.getEmpByyCondition(emp);
        System.out.println(list);
    }


2.若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的and去掉

    public void test7(){
        SqlSessionUtils sqlSessionUtils = new SqlSessionUtils();
        SqlSession sqlSession = sqlSessionUtils.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        Emp emp = new Emp(null,null,20,null);
        List<Emp> list = mapper.getEmpByyCondition(emp);
        System.out.println(list);
    }


3.trim


trim用于去掉或添加标签中的内容


常用属性:


prefix:在trim标签中的内容的前面添加某些内容


prefixOverrides:在trim标签中的内容的前面去掉某些内容


suffix:在trim标签中的内容的后面添加某些内容


suffixOverrides:在trim标签中的内容的后面去掉某些内容

    <select id="getEmpByyCondition" resultType="com.atguigu.mybatis.pojo.Emp">
        select * from t_emp
        <trim prefix="where" suffixOverrides="and">
            <if test="empName!=null and empName!=''">
                emp_name=#{empName} and
            </if>
            <if test="age!=null and age!=''">
                 age=#{age}and
            </if>
            <if test="gender!=null and gender!=''">
                gender=#{gender}
            </if>
        </trim>
    </select>

4.choose、when、otherwise


choose、when、 otherwise相当于if...else if..else

    <select id="getEmpByChoose" resultType="com.atguigu.mybatis.pojo.Emp">
        select * from t_emp
        <where>
            <choose>
                <when test="empName!=null and empName!=''">emp_name=#{empName} </when>
                <when test="age!=null and age!=''">ge=#{age} </when>
                <when test="gender!=null and gender!=''"> gender=#{gender}</when>
            </choose>
        </where>
    </select>
    public void test7(){
        SqlSessionUtils sqlSessionUtils = new SqlSessionUtils();
        SqlSession sqlSession = sqlSessionUtils.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        Emp emp = new Emp(null,"张三",21,null);
        List<Emp> list = mapper.getEmpByChoose(emp);
        System.out.println(list);
    }

因为when相当于else if    所以当前面有条件满足时,不会执行后面的when语句


 


5.foreach


collection: 需做foreach(遍历)的对象,作为入参时,list、array对象时,collection属性值分别默认用"list"、"array"代替,Map对象没有默认的属性值。但是,在作为入参时可以使用@Param(“keyName”)注解来设置自定义collection属性值,设置keyName后,list、array会失效;


item: 集合元素迭代时的别名称,该参数为必选项;


index: 在list、array中,index为元素的序号索引。但是在Map中,index为遍历元素的key值,该参数为可选项;


open: 遍历集合时的开始符号,通常与close=")"搭配使用。使用场景IN(),values()时,该参数为可选项;


separator: 元素之间的分隔符,类比在IN()的时候,separator=",",最终所有遍历的元素将会以设定的(,)逗号符号隔开,该参数为可选项;


close: 遍历集合时的结束符号,通常与open="("搭配使用,该参数为可选项;


1.批量添加数据

void insertEmps(@Param("emps") List<Emp> emps);
    <insert id="insertEmps">
        insert into t_emp value
        <foreach collection="emps" item="emp" separator=",">
          (null,#{emp.empName},#{emp.age},#{emp.gender},null)
        </foreach>
    </insert>
    public void test8(){
        SqlSessionUtils sqlSessionUtils = new SqlSessionUtils();
        SqlSession sqlSession = sqlSessionUtils.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        Emp emp1 = new Emp(null,"数据1",21,"女");
        Emp emp2 = new Emp(null,"数据2",24,"男");
        Emp emp3 = new Emp(null,"数据3",31,"女");
        List<Emp> emps = Arrays.asList(emp1, emp2, emp3);
        mapper.insertEmps(emps);
    }

运行结果:



添加数据前:


 



添加数据后:


2.批量删除数据

void  deleteByEmpIds(@Param("empIds") Integer[] empIds);
    <delete id="deleteByEmpIds">
        delete from t_emp where emp_id in
        <foreach collection="empIds" item="empId" separator="," open="(" close=")">
        #{empId}
    </foreach>
    </delete>
    public void test9(){
        SqlSessionUtils sqlSessionUtils = new SqlSessionUtils();
        SqlSession sqlSession = sqlSessionUtils.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        Integer empIds[]={6,7};
        mapper.deleteByEmpIds(empIds);
    }


方法2:

    <delete id="deleteByEmpIds">
        delete from t_emp where
        <foreach collection="empIds" item="empId" separator="or" >
            emp_id=#{empId}
        </foreach>
    </delete>

6.SQL片段


sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引

List<Emp> selectAll();
    <sql id="empColumns"> emp_id,emp_name,age,gender</sql>
    <select id="selectAll" resultType="com.atguigu.mybatis.pojo.Emp">
        select <include refid="empColumns"></include> from t_emp
    </select>
    public void test10(){
        SqlSessionUtils sqlSessionUtils = new SqlSessionUtils();
        SqlSession sqlSession = sqlSessionUtils.getSqlSession();
        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> emps = mapper.selectAll();
        System.out.println(emps);
    }
相关文章
|
2月前
|
SQL Java 数据库连接
2-SSM框架篇
Spring框架核心知识点总结,涵盖IOC、DI、Bean作用域、事务管理、AOP、Spring MVC流程及MyBatis相关问题。内容包括控制反转与依赖注入原理、Bean生命周期与线程安全、事务传播机制、JDK与CGLIB代理区别、MyBatis动态SQL与缓存机制等高频面试题。
42 0
|
2月前
|
SQL XML Java
配置Spring框架以连接SQL Server数据库
最后,需要集成Spring配置到应用中,这通常在 `main`方法或者Spring Boot的应用配置类中通过加载XML配置或使用注解来实现。
261 0
|
11月前
|
SQL 数据采集 自然语言处理
NL2SQL之DB-GPT-Hub<详解篇>:text2sql任务的微调框架和基准对比
NL2SQL之DB-GPT-Hub<详解篇>:text2sql任务的微调框架和基准对比
|
6月前
|
前端开发 Java 数据库连接
Spring MVC 扩展和SSM框架整合
通过以上步骤,我们可以将Spring MVC扩展并整合到SSM框架中。这个过程包括配置Spring MVC和Spring的核心配置文件,创建控制器、服务层和MyBatis的Mapper接口及映射文件。在实际开发中,可以根据具体业务需求进行进一步的扩展和优化,以构建更加灵活和高效的企业级应用程序。
140 5
|
6月前
|
SQL 缓存 Java
框架源码私享笔记(02)Mybatis核心框架原理 | 一条SQL透析核心组件功能特性
本文详细解构了MyBatis的工作机制,包括解析配置、创建连接、执行SQL、结果封装和关闭连接等步骤。文章还介绍了MyBatis的五大核心功能特性:支持动态SQL、缓存机制(一级和二级缓存)、插件扩展、延迟加载和SQL注解,帮助读者深入了解其高效灵活的设计理念。
|
10月前
|
SQL 监控 安全
Flask 框架防止 SQL 注入攻击的方法
通过综合运用以上多种措施,Flask 框架可以有效地降低 SQL 注入攻击的风险,保障应用的安全稳定运行。同时,持续的安全评估和改进也是确保应用长期安全的重要环节。
410 71
|
9月前
|
SQL 安全 Java
除了Flask框架,还有哪些框架能防止SQL注入攻击?
这些框架都在安全方面有着较好的表现,通过它们的内置机制和安全特性,可以有效地降低 SQL 注入攻击的风险。然而,无论使用哪个框架,开发者都需要具备良好的安全意识,正确配置和使用框架提供的安全功能,以确保应用的安全可靠。同时,持续关注安全更新和漏洞修复也是非常重要的。
289 61
|
7月前
|
Java 关系型数据库 MySQL
ssm063基于SSM框架的德云社票务系统的设计与实现(文档+源码)_kaic
基于SSM框架的德云社票务系统旨在解决传统相声订票方式费时费力的问题,提供便捷的在线订票平台。系统采用Java技术、MySQL数据库,结合B/S架构,确保数据安全性和操作简便性。用户可轻松查询、预订相声票务信息,管理员则能高效管理票务和会员信息。该系统功能齐全、运行稳定,适用于现代信息化生活需求,有效提升德云社的票务管理效率与用户体验。
|
9月前
|
SQL 存储 人工智能
Vanna:开源 AI 检索生成框架,自动生成精确的 SQL 查询
Vanna 是一个开源的 Python RAG(Retrieval-Augmented Generation)框架,能够基于大型语言模型(LLMs)为数据库生成精确的 SQL 查询。Vanna 支持多种 LLMs、向量数据库和 SQL 数据库,提供高准确性查询,同时确保数据库内容安全私密,不外泄。
1432 7
Vanna:开源 AI 检索生成框架,自动生成精确的 SQL 查询
|
8月前
|
SQL 分布式计算 Java
Spark SQL向量化执行引擎框架Gluten-Velox在AArch64使能和优化
本文摘自 Arm China的工程师顾煜祺关于“在 Arm 平台上使用 Native 算子库加速 Spark”的分享,主要内容包括以下四个部分: 1.技术背景 2.算子库构成 3.算子操作优化 4.未来工作
944 0