How does mybatis framework implement dynamic SQL?

HUIYL1 2020-11-10 10:41:05
mybatis framework implement dynamic sql


MyBatis One of its powerful features is its dynamics SQL. If you use JDBC Or other similar framework experience , And you can see that you can stitch together according to different conditions SQL How painful words are . When splicing, make sure you don't forget the necessary spaces , Also note that the comma at the end of the column name list is omitted . Using dynamics SQL This characteristic can get rid of this kind of pain completely . It helps ognl( Be similar to jsp Inside el expression ) Expression to complete the dynamic sql The stitching makes it very easy .

Internship dynamic SQL The way

  • if conditional
  • choose, when, otherwise Selector use
  • trim, where, set
  • foreach
  • Use Ognl expression

Case practice

if conditional

dynamic SQL The usual thing to do is to conditionally include where Part of clause . such as :

<!-- Fuzzy matching -->    
<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>

Use if The label is to add a test Attribute as a judgment , If there are more than one condition combination judgment, use and, or Connect

Implementation method

@Override    
public List<User> queryUserByUserName(String userName) {
   List<User> users=null;      
   SqlSession session=null;    
   try {          
       session=sqlSessionFactory.openSession();      
       Map map=new HashMap();
       //map Parameters          
       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;  
}

Running results , sql Automatic judgment and splicing

choose, when, otherwise Selector use

We don't want to use all the conditional statements , And just want to choose one or two of them . In this case ,MyBatis Provides choose Elements , It's a bit like Java Medium switch sentence

<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>

The meaning of this sentence is to say If I pass in nation Check if not empty userName Value , It is realName Value

@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

The previous examples have appropriately addressed a notorious dynamic SQL problem , Then let's look at the configuration of the first item

<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>

If I put userName like '%${userName}%' This sentence also uses if Make a judgment

<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 like '%${phone}%'  
   </if>
</select>

In this case, let's predict Printed sql Should be

select userId, userName, password from user where

Obviously this one sql Will report a mistake

In order to solve this problem , We use <where></where> label

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

Writing test classes

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

where Elements know only in more than one if Only insert when the condition has value “WHERE” Clause . and , If the last thing is “AND” or “OR” At the beginning ,where Elements also know how to remove them . Like the configuration above, if I phone Valuable , userName If it's not worth it where I also know that I will phone Ahead and Get rid of

But if where The element doesn't play the normal way , We can still customize trim Elements to customize the functionality we want . such as , and where Element equivalent customization trim Element is :

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

The effect is similar to <where></where> The effect is the same

prefixOverrides Property ignores pipe delimited text sequences ( Note that spaces in this example are also necessary ). The result of it is that everything is prefixOverrides Property will be removed , And insert prefix The content specified in the property .

about update sentence , We use <set></set> To set the value

<update id="updateUserById" parameterType="user">    
   update user          
   <set>      
       <if test="userName!=null">  
           userName=#{userName},      
       </if>      
       <if test="userPwd!=null">  
           userPwd=#{userPwd},    
       </if>      
   </set>    
   where id=#{id}
</update>

Write test methods

@Test  
public void test17(){  
   UserDao userDao=new UserDaoImpl(sqlSessionFactory);
   User user=userDao.queryUserById(6);      
   user.setUserPwd(null);    
   user.setUserName("xxx06");  
   userDao.updateUserById(user);
}

If you customize the equivalent trim Interested in the look of the elements , Then this should be its true face :

<update id="updateUserById" parameterType="user">      
   update user      
   <trim prefix="set" suffixOverrides="," > <!-- Use the suffix to eliminate , -->      
       <if test="userName!=null">      
           userName=#{userName},      
       </if>    
       <if test="userPwd!=null">    
           userPwd=#{userPwd},    
       </if>        
   </trim>        
   where id=#{id}
</update>

This effect and set It's consistent

foreach

dynamic SQL Another common necessary operation is to traverse a set , Usually in the build IN Conditional statements or batch inserts . such as :

<select id="findUserByUserName" resultMap="RM_User" >
   select    
    userId, userName, password  
   from  
    user  
   <where>  
       <if test="userNameList != null" >
           userName in  
           <foreach item="item" index="index" collection="userNameList"open="(" separator="," close=")">
               #{item}  
           </foreach>  
       </if>  
   </where>
</select>

Write test methods

@Test
public void testFindUserByUserName() {
   InputStream is = MybatisSecondaryCacheTest.class.getClassLoader().getResourceAsStream("mybatis.xml");  SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);  
   SqlSession session = sessionFactory.openSession();  
   // Create a parameter  
   Map<String, Object> params = new HashMap<>();
   // Create to string The array is then converted to list  
   String[] userName = new String[]{"Tonygogo", "hello", " Ha ha ha "};              params.put("userNameList", Arrays.asList(userName));
   // string Array rotation list, key The name of the mapping file should always be the same as the variable name in the mapping file  
   List<User> users = session.selectList("findUserByUserName", params);            System.out.println(" Query results : " + users.toString());
}

Use Ognl expression

We're in the mapping above , If you use if To determine whether a value is empty or an empty string, we do this test="userName != null and userName !='' " It's complicated to write like this , So we use Ognl expression @Ognl@isNotEmpty(userName) To judge .

Use ognl Expression, we need to add... Under the package of the root directory Ognl One of the Java class , There are all kinds of judgments, such as null judgment @Ognl@isEmpty(userName), Not empty judgment @Ognl@isNotEmpty(userName), Is it an empty string @Ognl@isBlank(userName), Not an empty string @Ognl@isNotBlank(userName)** wait

We may use these four , It's just convenient for us to do some operations , It's also used in practice

import java.lang.reflect.Array;
import java.util.Collection;import java.util.Map;  
/**

  • Ognl Tool class , Mainly in order to ognl Expression access to static methods can reduce the long class name writing
  • Ognl The expression for accessing static methods is : @class@method(args)
  •  
  • Example use :  
  • <pre>
  •  <if test="@Ognl@isNotEmpty(userId)">
  •      and user_id = #{userId}
  •  </if>
  • </pre>

*/
public class Ognl {        
   /**    
   * Can be used to judge String,Map,Collection,Array Is it empty    
   * @param o    
   * @return    
   */    
   @SuppressWarnings("rawtypes")    
   public static boolean isEmpty(Object o) throws IllegalArgumentException {        
       if(o == null) return true;        
       if(o instanceof String) {            
           if(((String)o).length() == 0){          
               return true;          
           }      
       } else if(o instanceof Collection) {    
           if(((Collection)o).isEmpty()){    
               return true;      
           }        
       } else if(o.getClass().isArray()) {  
           if(Array.getLength(o) == 0){      
               return true;        
           }      
       } else if(o instanceof Map) {  
           if(((Map)o).isEmpty()){    
               return true;      
           }      
       }else {    
           return false;
           //          throw new IllegalArgumentException("Illegal argument type,must be : Map,Collection,Array,String. but was:"+o.getClass());      
       }      
       return false;  
   }        
   /**    
   * Can be used to judge Map,Collection,String,Array Whether it is not empty    
   * @param c  
   * @return  
   */    
   public static boolean isNotEmpty(Object o) {    
       return !isEmpty(o);  
   }      
   public static boolean isNotBlank(Object o) {  
       return !isBlank(o);  
   }    
   public static boolean isBlank(Object o) {    
       if(o == null)      
           return true;    
       if(o instanceof String) {    
           String str = (String)o;      
           return isBlank(str);    
       }      
       return false;
   }    
   public static boolean isBlank(String str) {    
       if(str == null || str.length() == 0) {  
           return true;      
       }          
       for (int i = 0; i < str.length(); i++) {    
           if (!Character.isWhitespace(str.charAt(i))) {  
               return false;      
           }    
       }    
       return true;
   }
}

Expand

Annotation form dynamic sql

except xml Configuration can support dynamic sql Outside ,MyBatis Various annotations such as @InsertProvider,@UpdateProvider,@DeleteProvider and @SelectProvider, To help build dynamic SQL sentence , And then let MyBatis Carry out these SQL sentence .

public interface AccountDao {
•    /**
•     * Add account records  
•     *   Add string sql from AccountProvider class addAccount Method provides
•     *   Returns the number of affected rows
•     * @param account
•     * @return
•     */
•    @InsertProvider(method="addAccount",type=AccountProvider.class)
•    public int  addAcccount(Account account);
•    
•    /**
•     * Add account records  
•     *   Add string sql from AccountProvider class addAccount Method provides
•     * Return primary key
•     * @param account
•     * @return
•     */
•    @InsertProvider(method="addAccount",type=AccountProvider.class)
•    @Options(useGeneratedKeys=true,keyColumn="id")
•    public int  addAcccount02(Account account);
•    
•    /**
•     * according to id Check account records  
•     *   Query string sql from AccountProvider class queryAccountById Method provides
•     * @param id
•     * @return
•     */
•    @SelectProvider(method="queryAccountById",type=AccountProvider.class)
•    public Account queryAccountById(@Param("id")int id);
•    
•    /**
•     * Multi condition query account records
•     *   Query string sql from AccountProvider class queryAccountByParams Method provides
•     * @param aname
•     * @param type
•     * @param time
•     * @return
•     */
•    @SelectProvider(method="queryAccountByParams",type=AccountProvider.class)
•    public List<Account> queryAccountByParams(@Param("aname")String aname,@Param("type")String type,@Param("time")String time);
•    
•    /**
•     * Update account records
•     *   Update string sql from AccountProvider class updateAccountById Method provides
•     * @param account
•     * @return
•     */
•    @UpdateProvider(method="updateAccount",type=AccountProvider.class)
•    public int updateAccountById(Account account);
•    
•    /**
•     * according to id Delete account records
•     *   Delete string sql from AccountProvider class deleteAccount Method provides
•     * @param id
•     * @return
•     */
•    @DeleteProvider(method="deleteAccount",type=AccountProvider.class)
•    public int deleteAccountById(@Param("id")int id);
}
public class AccountProvider {
•    /**
•     * Return to add account record sql character string
•     * @param account
•     * @return
•     */
•    public String addAccount(final Account account){
•        return new SQL(){{
•            INSERT_INTO("account");
•            VALUES("aname","#{aname}");
•            VALUES("type", "#{type}");
•            VALUES("remark","#{remark}");
•            VALUES("money", "#{money}");
•            VALUES("user_id", "#{userId}");
•            VALUES("create_time","#{createTime}");
•            VALUES("update_time", "#{updateTime}");
•        }}.toString();
•    }
•    
•    /**
•     * Return according to id Check account records sql character string
•     * @param id
•     * @return
•     */
•    public String queryAccountById(@Param("id")int id){
•        return new SQL(){{
•            SELECT("id,aname,type,remark,create_time as createTime,update_time as updateTime,user_id as userId");
•            FROM("account");
•            WHERE(" id=#{id} ");
•        }}.toString();
•    }
•    
•    /**
•     * Return multi condition query sql character string
•     * @param aname
•     * @param type
•     * @param time
•     * @return
•     */
•    public String queryAccountByParams(@Param("aname") final String aname,@Param("type")final String type,@Param("time")final String time){
•        String sql= new SQL(){{
•            SELECT("id,aname,type,remark,create_time as createTime,update_time as updateTime,user_id as userId");
•            FROM("account");
•            WHERE(" 1=1 ");
•            if(!StringUtils.isNullOrEmpty(aname)){
•                AND();
•                WHERE(" aname like concat('%',#{aname},'%') ");
•            }
•            if(!StringUtils.isNullOrEmpty(type)){
•                AND();
•                WHERE(" type =#{type}");
•            }
•            if(!StringUtils.isNullOrEmpty(time)){
•                AND();
•                WHERE(" create_time <=#{time}");
•            }
•        }}.toString();
•        return sql;
•    }
•    
•    /**
•     * Return to update account records sql character string
•     * @param account
•     * @return
•     */
•    public String updateAccount(Account account){
•         return new SQL(){{
•               UPDATE(" account");
•               SET("aname=#{aname}");
•               SET("type=#{type}");
•               WHERE("id=#{id}");
•         }}.toString();
•    }
•    
•    /**
•     * Return to delete account record sql character string
•     * @param id
•     * @return
•     */
•    public String deleteAccount(@Param("id")int id){
•        return new SQL(){{
•            DELETE_FROM("account");
•            WHERE("id=#{id}");
•        }}.toString();
•    }
}
版权声明
本文为[HUIYL1]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云