mybatis动态SQL

动态 SQL-参考链接
有兴趣深究的可以去查看mybatis-3-mapper.dtd这个文件。
http://mybatis.org/dtd/mybatis-3-config.dtd

1.组装update

    
        update node
        
            
                node_name = #{nodeName,jdbcType=VARCHAR},
            
            
                note = #{note,jdbcType=VARCHAR},
            
        
        where node_id = #{nodeId,jdbcType=INTEGER}
    

使用set,if 。第二个if判断里面也是有逗号结尾,真正组装成sql之后,提供的功能会把最后的“,”给trim掉。

2.组装select


使用where,if 。如果第一个if没匹配到,匹配到第二个if,开头的AND会被给去掉trim。OR也会被去掉(如果有OR的话)。

3.组装insert

上面的,都是已经实现好的功能(等价于自定义trim),如果没有自己需要的,可以自定义trim。比如insert:

    
        insert into node  
        
            
                node_id,
            
            
                node_name,
            
            
                note,
            
        
        
            
                #{nodeId,jdbcType=INTEGER},
            
            
                #{nodeName,jdbcType=VARCHAR},
            
            
                #{note,jdbcType=VARCHAR},
            
        
    

prifix前缀;
suffix后缀;
suffixOverrides后缀赘余符,第三个note如果匹配到,后面的逗号会被处理掉;
同样也有前缀赘余符,prefixOverrides 。比如先前的,如果自定义实现组装select的话:


如果要like做%?%通配查询,可以用以下三种方式:

  1. 传参数直接用%%包裹传过来
  2. concat(推荐用这种方式)
    
实际上在输出sql的时候(我的搜索内容是“tn”),组装的sql如下:
2018-07-03 14:21:42  DEBUG ****.mapper.NodeMapper.selectConditional ==>  Preparing: select node_id, node_name, note from node WHERE node_name like concat(concat('%',?),'%') 
2018-07-03 14:21:42  DEBUG ****.mapper.NodeMapper.selectConditional ==> Parameters: tn(String)
  1. bind(这种方式存在一定的问题,比如下面代码中如果nodeName传过来的时候是null会报错,建议用方式2 concat)
    
实际上在输出sql的时候(我的搜索内容是“tn”),组装的sql如下:
2018-07-03 14:24:53  DEBUG ****.mapper.NodeMapper.selectConditional ==>  Preparing: select node_id, node_name, note from node WHERE node_name like ? 
2018-07-03 14:24:53  DEBUG ****.mapper.NodeMapper.selectConditional ==> Parameters: %tn%(String)

4. delete

你可能感兴趣的:(mybatis动态SQL)