MyBatis dynamic SQL (annotated version)

table of Contents

 

One, script

 

Two, the expression of OGNL

1.if 

2. choose

3.where

4.Set

5.bind

 6.foreach

Three, about the constructor of JavaBean

Four, dynamic sql example

Five, write sql in the method

1. @InsertProvider realizes batch insertion of data

2、@SelectProvider  in List

Six, Mybatis official documents


One, script

In the annotation version, to use dynamic SQL, you need to include the sql statement in the script tag.

When using special symbols in <script></script>, use java escape characters, such as double quotation marks "" use "" instead or use \"\" 

<script></script>

 

Two, the expression of OGNL

1.if 

By judging the dynamic splicing of SQL statements, it is generally used to judge the query conditions

<if test=''>...</if>

2. choose

Choose according to conditions

<choose>
    <when test=''> ...
    </when>
    <when test=''> ...
    </when>
    <otherwise> ...
    </otherwise> 
</choose>

3.where

Generally used in conjunction with if or choose, these tags may remove redundant keywords or symbols. The where  element inserts the "WHERE" clause only if the child element returns any content. Moreover, if the beginning of the clause is "AND" or "OR", the where  element will also remove them. Such as

<where>
    <if test="id != null "> 
        and t_id = #{id}
    </if>
</where>

4.Set

A similar solution for dynamic update statements is called  set . The set  element can be used to dynamically include columns that need to be updated, ignoring other columns that are not updated. The set  element dynamically inserts the SET keyword at the beginning of the line and deletes the extra comma. such as:

<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>

5.bind

Bind a value, which can be applied to the query statement

<bind name="" value="" />

 6.foreach

Loop, which can traverse the incoming and collection. In general used for batch updates and query statements

<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
    #{item}
</foreach>

(1) item: the element of the collection, access the Filed of the element use #{item.Filed}

(2) index: subscript, counting from 0

(3) collection: the incoming collection parameters

(4) open: what to start with

(5) separator: what to use as the separator

(6) close: what ends with

For example, the incoming list is a List<String>: ["a","b","c"], the result of the foreach above is: ("a", "b", "c").

 

Three, about the constructor of JavaBean

(1) The bean has only one constructor with parameters. MyBatis calls the constructor (parameters are in order). At this time, the @results annotation is invalid. And when the number of query results is inconsistent with the constructor, an exception will be reported.
(2) The bean has multiple constructors and there is no parameterless constructor. MyBatis calls the constructor with the same number of query fields; if there is no constructor with the same number, an exception will be reported.
(3) The bean has multiple construction methods, and there is a parameterless constructor. MyBatis calls the parameterless constructor.
(4) In summary, under normal circumstances, beans do not define a constructor with parameters; if necessary, please define a constructor without parameters.

 

Four, dynamic sql example

/**
     * if 对内容进行判断
     * concat函数:mysql拼接字符串的函数
     */
    @Select("<script>"
            + "select t_id, t_name, t_age                          "
            + "from sys_user                                       "
            + "<where>                                             "
            + "  <if test='id != null and id != ""'>     "
            + "    and t_id = #{id}                                "
            + "  </if>                                             "
            + "  <if test='name != null and name != ""'> "
            + "    and t_name like CONCAT('%', #{name}, '%')       "
            + "  </if>                                             "
            + "</where>                                            "
            + "</script>                                           ")
    @Results(id="userResults", value={
        @Result(property="id",   column="t_id"),
        @Result(property="name", column="t_name"),
        @Result(property="age",  column="t_age"),
    })
    List<User> selectUserWithIf(User user);
    
    /**
     * choose when otherwise 类似Java的Switch,选择某一项
     * when...when...otherwise... == if... if...else... 
     */
    @Select("<script>"
            + "select t_id, t_name, t_age                                     "
            + "from sys_user                                                  "
            + "<where>                                                        "
            + "  <choose>                                                     "
            + "      <when test='id != null and id != ""'>          "
            + "            and t_id = #{id}                                   "
            + "      </when>                                                  "
            + "      <otherwise test='name != null and name != ""'> "
            + "            and t_name like CONCAT('%', #{name}, '%')          "
            + "      </otherwise>                                             "
            + "  </choose>                                                    "
            + "</where>                                                       "
            + "</script>                                                      ")
    @ResultMap("userResults")
    List<User> selectUserWithChoose(User user);
    
    /**
     * set 动态更新语句,类似<where>
     */
    @Update("<script>                                           "
            + "update sys_user                                  "
            + "<set>                                            "
            + "  <if test='name != null'> t_name=#{name}, </if> "
            + "  <if test='age != null'> t_age=#{age},    </if> "
            + "</set>                                           "
            + "where t_id = #{id}                               "
            + "</script>                                        ")
    int updateUserWithSet(User user);
    
    /**
     * foreach 遍历一个集合,常用于批量更新和条件语句中的 IN
     * foreach 批量更新
     */
    @Insert("<script>                                  "
            + "insert into sys_user                    "
            + "(t_id, t_name, t_age)                   "
            + "values                                  "
            + "<foreach collection='list' item='item'  "
            + " index='index' separator=','>           "
            + "(#{item.id}, #{item.name}, #{item.age}) "
            + "</foreach>                              "
            + "</script>                               ")
    int insertUserListWithForeach(List<User> list);
    
    /**
     * foreach 条件语句中的 IN
     */
    @Select("<script>"
            + "select t_id, t_name, t_age                             "
            + "from sys_user                                          "
            + "where t_name in                                        "
            + "  <foreach collection='list' item='item' index='index' "
            + "    open='(' separator=',' close=')' >                 "
            + "    #{item}                                            "
            + "  </foreach>                                           "
            + "</script>                                              ")
    @ResultMap("userResults")
    List<User> selectUserByINName(List<String> list);
    
    /**
     * bind 创建一个变量,绑定到上下文中
     */
    @Select("<script>                                              "
            + "<bind name=\"lname\" value=\"'%' + name + '%'\"  /> "
            + "select t_id, t_name, t_age                          "
            + "from sys_user                                       "
            + "where t_name like #{lname}                          "
            + "</script>                                           ")
    @ResultMap("userResults")
    List<User> selectUserWithBind(@Param("name") String name);

 

Five, write sql in the method

@InsertProvider 
@UpdateProvider 
@DeleteProvider 
@SelectProvider

 

1. @InsertProvider realizes batch insertion of data

MySql batch insert database statement format:

INSERT INTO 

[表名]([列名],[列名]) 

 VALUES

([列值],[列值])),

([列值],[列值])),

([列值],[列值]));

E.g:

INSERT INTO 

items(name,city,price,number,picture) 

VALUES

('耐克运动鞋','广州',500,1000,'003.jpg'),

('耐克运动鞋2','广州2',500,1000,'002.jpg');

Entity class:

public class WetSortVillage {
    
    private Integer id;
    
    private Integer areaId;
    
    private String areaName;
    
    private Integer streetId;
    
    private String village;
    
    private String street;
    
    private Integer villageId;
    
    private Integer households;//户数
    
    private Integer kegStationNum;//桶站数
    
    private Integer workerNum;//分类员数量
    
    private Integer status;//有效状态 1:开启 2关闭   默认添加就是开启
}

mapper:

public interface WetSortVillageMapper {

@InsertProvider(type=SQLProvider.class,method="insertSortVillagesByParam")
    public int insertSortVillagesByParam(List<WetSortVillage> list);
}

SQLProvider.java :

  public String insertSortVillagesByParam(Map map){
        StringBuilder sb = new StringBuilder();
        List<WetSortVillage> list = (List<WetSortVillage>) map.get("list");
        sb.append("INSERT INTO t_wet_sort_village ");
        sb.append("(area_id,street_id,village_id,households,");
        sb.append("keg_station_num,worker_num,status)");
        sb.append(" VALUES ");
        int length = list.size();
        MessageFormat mf = new MessageFormat("(#'{'list[{0}].areaId},#'{'list[{0}].streetId},#'{'list[{0}].villageId},#'{'list[{0}].households}"
                + ",#'{'list[{0}].kegStationNum},#'{'list[{0}].workerNum},#'{'list[{0}].status})");
        for(int i=0;i<length;i++){
             sb.append(mf.format(new Object[]{i}));  
             sb.append(StringUtils.join(valueArray, ","));
        }
    
        return sb.toString();
 }

2、@SelectProvider  in List

@Select({"<script>", +

"select ", +

"mysection ", +

"from test_my_table ", +

"where myNo in ", +

"<foreach collection='userDefParamName' item='yourselfItem' open='(' separator=',' close=')'>", +

"#{yourselfItem}", +

"</foreach>"

})

String getMysection (@Param("userDefParamName")List whateverName);

Use the <foreach> method to report an error. It is said that the version is low. If you use the version above 3.5.1, you can verify by yourself.

The following describes the solution for this version:

public String getMysection (@Param("userDefParamName")List whateverName){

    StringBuffer sql =new StringBuffer();

    sql.append("select mysection  from test_my_table ");

    sql.append(" where myNo IN ");

    if(userDefParamName.size()>0) {

    sql.append("(");

    for (int i =0; i < userDefParamName.size(); i++) {

    if(i>0){

        sql.append(",");

    }

    sql.append("#{userDefParamName[");

    sql.append(i);

    sql.append("]}");

    }

    sql.append(")");

    }

    return sql.toString() ;
}

 

Six, Mybatis official documents


https://mybatis.org/mybatis-3/zh/index.html

Guess you like

Origin blog.csdn.net/xiao__jia__jia/article/details/110975745