栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

mybatis中动态`SQL`

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

mybatis中动态`SQL`

动态SQL

mybatis框架的动态sql技术是一种根据特定条件动态拼装sql语句的功能,它存在单方是为了解决拼接sql语句字符串时痛点问题

动态sql就是解决我们拼接sql语句的麻烦

1.if标签【重点】

标签属性test所对应的表达式决定在标签中的内容是否需要拼接到SQL中,并且在where之后加入一个恒成立条件1=1

在where的后面加入恒成立条件1=1的原因是,防止后面所有的条件都不成功,where多余后报错,同时还防止第一个条件不成立,在where的后面直接跟着and造成报错

注意是:在if标签中可以直接使用传入对象中的属性

例如:


     and 字段名 = #{传入值}【字段名是对应表中字段名否则报错】

案例:

Mapper接口

    // 由于不知道传入是邮箱还是年龄还是性别等,所以直接将传入的信息封装成对象
    Emp getEmpByDynamics(Emp emp);

Mapper.xml文件


    
        select * from emp where 1=1
        
            and emp_name = #{empName}
        
        
            and age = #{age}
        
        
            and sex = #{sex}
        
        
            and email = #{email}
        
    

test类

 // if标签
    @Test
    public void testGetEmpByDynamics(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DynamicsMapper mapper = sqlSession.getMapper(DynamicsMapper.class);
        Emp emp = mapper.getEmpByDynamics(new Emp(null, "海康", 21, "男", ""));
        System.out.println(emp);
    }
2.where标签【重点】

where和if一般结合使用:

  • 若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
  • 若where标签中的if条件满足,则where标签自动添加where关键字,并将条件最前面多余的and或or去掉

注意是:where标签不能去掉最后多余的and或or,所以不能把and或or写到后面

案例:

Mapper接口

// 由于不知道传入是邮箱还是年龄还是性别等,所以直接将传入的信息封装成对象
    List getEmpByDynamics(Emp emp);

Mapper.xml文件


    
        select * from emp
        
            
                
                    emp_name = #{empName}
                
                
                    age = #{age}
                
                
                    sex = #{sex}
                
                
                    email = #{email}
                
                
                
                    did = 1
                
            
        
    

test类

// `choose  when   otherwise`标签
    @Test
    public void testGetEmpChoose(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DynamicsMapper mapper = sqlSession.getMapper(DynamicsMapper.class);
        // 返回sql: select * from emp WHERe age = ? ,说明只要有一个条件when时,当执行when中内容,
        // 并跳转该语句,如果都不满足,则执行otherwise中的内容
        List list = mapper.getEmpByChoose(new Emp(null, "", 21, "男", ""));
        //
        list.forEach(emp -> System.out.println(emp));
    }

5.foreach标签【非常重点】

属性:

collection:设置要循环的数组或集合

item:表示集合或数组中每个数据

separator:设置循环体之间的分隔符

open:设置foreach标签中的内容的开始符

close:设置foreach标签中的内容的结束符



collection表示集合或数组
item表示集合或数组中的每个元素
open表示以'('开始【应用在需要使用括号的sql语句中】
close表示以')'结束【应用在需要使用括号的sql语句中】

open 与 close搭配使用,表示在循环最外添加一个括号  例如:只在where ... in 中使用,不建议使用,需要括号自己手动添加

 delete from emp where eid in
       ( 
                #{eid}
             
        )
        
      
 与下面的等价的
 
  delete from emp where eid in
        
            #{eid}
        
        

open 与 close搭配使用,表示在循环最外添加一个括号 例如:只在where ... in 中使用,不建议使用,需要括号自己手动添加

案例:动态删除多条数据【批量删除】

Mapper接口

    int deleteMoreByArray(@Param("eids")Integer[] eids);

Mapper.xml文件


    



    delete from emp where
    
        eid=#{eid}
    



    

test类

// 批量删除多条数据
    @Test
    public void testDeleteMoreByArray(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DynamicsMapper mapper = sqlSession.getMapper(DynamicsMapper.class);
        Integer[] eids =  {9,10,20};
        int result = mapper.deleteMoreByArray(eids);
        System.out.println(result);
    }

案例2:批量添加
注意是由于在List中存放的是每个Emp对象,所以需要获取Emp中的属性需要使用emp对象名.的形式访问

Mapper接口

 // 动态添加多条数据
    int insertMoreByList(@Param("emps") List emps);

Mapper.xml文件


    
        insert into emp values
        
            (null,#{emp.empName},#{emp.age},#{emp.sex},#{emp.email},null)
            
        
    

test类

 // 批量添加多条数据
    @Test
    public void testInsertMoreByList(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DynamicsMapper mapper = sqlSession.getMapper(DynamicsMapper.class);
        Emp emp1 = new Emp(null, "a1", 22, "男", "123@qq.com");
        List list = Arrays.asList(emp1, emp1, emp1);
        int result = mapper.insertMoreByList(list);
       //返回sql: insert into emp values (null,?,?,?,?,null) , (null,?,?,?,?,null) , (null,?,?,?,?,null)
        System.out.println(result);
    }

6.sql标签

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

使用的步骤是:

1.先声明sql片段


	eid,ename,age,sex,did


2.引用sql片段

select  from t_emp

综合

Mapper接口

public interface DynamicsMapper {
    
    // 由于不知道传入是邮箱还是年龄还是性别等,所以直接将传入的信息封装成对象
    List getEmpByDynamics(Emp emp);

    
    List getEmpByChoose(Emp emp);

    
    int deleteMoreByArray(@Param("eids")Integer[] eids);

    // 动态添加多条数据
    int insertMoreByList(@Param("emps") List emps);
}

Mapper.xml文件



    
        insert into emp values
        
            (null,#{emp.empName},#{emp.age},#{emp.sex},#{emp.email},null)
            
        
    


    



    delete from emp where
    
        eid=#{eid}
    


    

    
        select * from emp
        
            
                emp_name=#{empName} and
            
            
                age=#{age} and
            
            
                sex=#{sex} and
            
            
                email=#{email}
            
        
    

    
        select * from emp where 1=1
        
            and emp_name = #{empName}
        
        
            and age = #{age}
        
        
            and sex = #{sex}
        
        
            and email = #{email}
        
    


test类

public class TestDynamicsMapper {
    // `choose  when   otherwise`标签
    @Test
    public void testGetEmpChoose(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DynamicsMapper mapper = sqlSession.getMapper(DynamicsMapper.class);
        // 返回sql: select * from emp WHERe age = ? ,说明只要有一个条件when时,当执行when中内容,
        // 并跳转该语句,如果都不满足,则执行otherwise中的内容
        List list = mapper.getEmpByChoose(new Emp(null, "", 21, "男", ""));
        //
        list.forEach(emp -> System.out.println(emp));
    }

    // if标签与where标签与trim标签
    @Test
    public void testGetEmpByDynamics(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DynamicsMapper mapper = sqlSession.getMapper(DynamicsMapper.class);
        // 返回的sql:select * from emp where age=? and sex=?
        List list = mapper.getEmpByDynamics(new Emp(null, "", 21, "男", ""));
        list.forEach(emp -> System.out.println(emp));
    }

    // 批量删除多条数据
    @Test
    public void testDeleteMoreByArray(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DynamicsMapper mapper = sqlSession.getMapper(DynamicsMapper.class);
        Integer[] eids =  {9,10,20};
        int result = mapper.deleteMoreByArray(eids);
        System.out.println(result);
    }

    // 批量添加多条数据
    @Test
    public void testInsertMoreByList(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DynamicsMapper mapper = sqlSession.getMapper(DynamicsMapper.class);
        Emp emp1 = new Emp(null, "a1", 22, "男", "123@qq.com");
        List list = Arrays.asList(emp1, emp1, emp1);
        int result = mapper.insertMoreByList(list);
       //返回sql: insert into emp values (null,?,?,?,?,null) , (null,?,?,?,?,null) , (null,?,?,?,?,null)
        System.out.println(result);
    }
}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/859510.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号