你知道Mybatis 框架如何实现 动态 SQL 吗?

需要更多相关资料的小可爱们,请看主页中的个人简介哦!

MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦。拼接的时候要确保不能忘了必要的空格,还要注意省掉列名列表最后的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。它借助ognl(类似于jsp里面的el表达式)表达式来完成动态sql的拼接使得非常简便。

实习 动态 SQL 的方式

  • if条件判断

  • choose, when, otherwise 选择器使用

  • trim, where, set

  • foreach

  • 使用Ognl表达式

案例实操

if条件判断

动态 SQL 通常要做的事情是有条件地包含 where 子句的一部分。比如:

<!-- 模糊匹配 -->    
<select id="queryUserByUserName" parameterType="string" resultType="user">    
    select id,userName,userPwd from user   where 1=1  
    <if test="userName!=null and userName!=''">      
        and userName like '%#{userName}%'       
    </if>
</select>

使用if标签就是加一个test属性作为判断, 如果有多个条件组合判断的话用and, or连接

实现方法

@Override    
public List<User> queryUserByUserName(String userName) {
    
    List<User> users=null;       
    SqlSession session=null;    
    try {
              
        session=sqlSessionFactory.openSession();      
        Map map=new HashMap();
        //map 参数           
        map.put("userName",userName);
        users=session.selectList("com.xxx.mapper.UserMapper.queryUserByUserName", map);        
    } catch (Exception e) {
          
        e.printStackTrace();     
    }finally{
               
        if(null!=session){
        
            session.close();      
        }            
    }      
    return users;   
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OD3gM2pH-1608534810732)(https://imgkr2.cn-bj.ufileos.com/6c5fe387-492c-4721-89aa-c8560f6a528f.png?UCloudPublicKey=TOKEN_8d8b72be-579a-4e83-bfd0-5f6ce1546f13&Signature=bC8cFRwCZAEavYH%252FBpq18iDwJ1Y%253D&Expires=1596378864)]

运行结果, sql自动判断并且拼接上了

choose, when, otherwise 选择器使用

我们不想用到所有的条件语句,而只想从中择其一二。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句

<select id="queryUserByParams" parameterType="map" resultType="user">        
    select id,userPwd       
    <choose>          
        <when test="nation!=null and nation!=''">      
            ,userName      
        </when>         
        <otherwise>     
            ,realName    
        </otherwise>       
    </choose>        
    from user      
    where userName like '%${userName}%'  
    <if test="phone!=null and phone!=''">   
        and phone like '%${phone}%'    
    </if>
</select>

这条语句的意思就是说 如果我传进nation不为空就查userName的值, 否则是realName的值

@Test    
public void test16(){
      
    UserDao userDao=new UserDaoImpl(sqlSessionFactory);    
    List<User> list=userDao.queryUserByParams("", null, "xxx"); 
    for(User u:list){
        
        System.out.println(u);   
    }  
}

trim, where, set

前面几个例子已经适宜地解决了一个臭名昭著的动态 SQL 问题, 然后我们再来看第一条的配置

<select id="findUserByUserName" resultMap="RM_User" >		
    select 			
    	userId, userName, password 		
    from 		
   	 	user 	
    where 		
    	userName like '%${userName}%'	
    <if test="phone != null and phone != ''" >		
        and phone like '%${phone}%'	
    </if>	
</select>

如果我把 userName like '%${userName}%'这个语句也用if做个判断

<select id="findUserByUserName" resultMap="RM_User" >	
    select 			
    	userId, userName, password 		
    from 	
    	user         
    where	   
    <if test="userName != null and userName != ''" >	
        userName like '%${userName}%'	  
    </if>	     
    <if test="phone != null and phone != ''" >	
        and phone lik
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值