MyBatis (dynamic SQL)

if: judge

choose (when, otherwise): branch selection, similar to the switch-case java

  If you use the id with the id check, if it is used with the lastName lastName check; only enter one

trim: string interception (WHERE (query package), set (condition modified package))

foreach

First, the use if

 

When queried, if certain conditions are not assembled band may be a problem sql

1, coupled to the back where 1 = 1, since the conditions and xxx;

2, MyBatis to use the label where all the query conditions are included. MyBatis where it will be assembled in the tag sql, extra and or or removed. ( Only remove the first extra and or or ), and or or are on the left.

    // carry the condition on which the query field value of this field to bring 
    public List <the Employee> getEmpsByConditionIf (the Employee the Employee);
    <-! Inquiry staff requirements: a field which carries the query to bring the value of this field -> 
    < the SELECT the above mentioned id = "getEmpsByConditionIf" resultType = "emp" > 
      the SELECT * from tbl_employee 
      < the WHERE > 
          ! <- 
              the Test : judgment expression (OGNL) 
              using OGNL reference document or Baidu official 
              from the parameter value is judged 
              to meet the special symbol should write an escape character; 
           -> 
          < IF the Test = "the above mentioned id = null!" > 
            the above mentioned id = {the above mentioned id # } 
          </ IF > 
          < IF Test = "lastName! = null and lastName! = ''" >
              and last_name like #{lastName}
          </IF > 
          < IF Test = "! = null and email.trim In Email () = ''!" > 
              and In Email # = {} In Email 
          </ IF > 
            <-! the OGNL determination will convert strings and numbers - > 
          < IF Test = "Gender or Gender == == 0. 1" > 
              and Gender Gender = # {} 
          </ IF > 
      </ WHERE > 
    </ SELECT >

 Second, the use trim (not used)

    public List<Employee> getEmpsByConditionTrim(Employee employee);
    < SELECT ID = "getEmpsByConditionTrim" the resultType = "EMP" > 
      SELECT * from tbl_employee 
      ! <- back and or extra or, where the label can not solve 
        prefix = "": Prefix: trim tab body fight the entire string string results after. prefix to the entire string is a prefix string fight 
        prefixOverrides = "": override prefix: removing the entire front of the extra character string 
        suffix = "": Suffix: suffix string to the entire plus a suffix string fight 
        suffixOverrides = "" suffix cover: remove the excess entire character string following 
      -> 
      < TRIM prefix = "WHERE" suffixOverrides = "and" > 
        < IF Test = "null ID ="! > 
            ID # = {ID} and 
        <
        test="lastName!=null and lastName!=''">
            last_name like #{lastName} and
        </if>
        <if test="email!=null and email.trim()!=''">
            email=#{email} and
        </if>
        <if test="gender==0 or gender==1">
            gender=#{gender}
        </if>
      </trim>
    </select>

Third, the use choose

    public List<Employee> getEmpsByConditionChoose(Employee employee);
    < The SELECT id = "getEmpsByConditionChoose" resultType = "emp" > 
        the SELECT * from tbl_employee 
        < the WHERE > 
            <-! If you check with the id with the id, lastName if brought on by lastName check; only enter one -> 
            < the Choose > 
                <-! if -> 
                < When Test = "! = null ID" > 
                    ID # = {ID} 
                </ When > 
                < When Test = "!! = null lastName and lastName = ''" > 
                    last_name } # {lastName like 
                </when>
                <when test="email!=null">
                    email=#{email}
                </when>
                <!--否则-->
                <otherwise>
                    gender=0
                </otherwise>
            </choose>
        </where>
    </select>

Four, set

set Tags: When changing employee information, do not need to rewrite all the data, just pass values ​​can be modified, the other value will not be modified.

    public void updateEmp(Employee employee);
    <update id="updateEmp">
          update tbl_employee
          <!-- set标签取出多余的逗号 -->
          <set>
              <if test="lastName!=null">
                  last_name=#{lastName},
              </if>
              <if test="email!=null">
                  email=#{email},
              </if>
              <if test="gender!=null">
                  gender=#{gender}
              </if>
          </set>
          where id= #{id}
    </update>

 Use trim Tags: remove the extra commas

     <update id="updateEmp">
       update tbl_employee
        <trim prefix="set" suffixOverrides=",">
            <if test="lastName!=null">
                last_name=#{lastName},
            </if>
            <if test="email!=null">
                email=#{email},
            </if>
            <if test="gender!=null">
                gender=#{gender}
            </if>
        </trim>
        where id= #{id}
    </update>

Fifth, use foreach

 Interface code:

    public List<Employee> getEmpsbyCondtionForeach(List<Integer> ids);

xml Code:

    <! - more id id in query information === (, 2, 3) -> 
    < the SELECT id = "getEmpsbyCondtionForeach" resultType = "emp" > 
        the SELECT * from tbl_employee in the WHERE id 
        <-! Collection: specifies a set of traverse: 
                List type specific treatment parameters encapsulated in the map, map the key is List 
             Item: assign an element of the current iteration specified variables 
             separator: separator between each element 
             open: traversing a All results stitching a character begins 
             close: traversing all the result of splicing the end of a character 
             index: index. The list is traversed when the index is an index, item is the current value 
                         is the key map indicates the traversing map index, item values that map 

             # {} variable name can be extracted variable value, which is the current traversing the element 
         -> 
        < foreach Collection="list" item="item_id" separator=","
                open="(" close=")">
            #{item_id}
        </foreach>
    </select>

Sixth, batch save

Database SQL:

/*批量保存*/
INSERT INTO tbl_employee(last_name,email,gender,d_id)
VALUES('Krystal','[email protected]','0',1),('Henry','[email protected]','1',2);

Interface code:

    public void addEmps(@Param("emps") List<Employee> emps);

 xml Code:

    <! - Batch save -> 
    <! - Edit saved under MySQL: mysql support can traverse foreach (), (), () syntax -> 
    < INSERT the above mentioned id = "addEmps" > 
        <! - Batch save XJS -> 
        the INSERT the INTO tbl_employee (last_name, In Email, Gender, D_ID) 
        the VALUES 
        < the foreach Collection = "the emps" Item = "EMP" Separator = "," > 
            (# emp.lastName {}, {#} emp.email, # emp.gender} {,} # {emp.dept.id) 
        </ the foreach > 
    </ INSERT > <-! recommended ->

or

Url need to add back the profile database parameters:

allowMultiQueries: In a statement, allows the use of ";" to separate multiple queries (true / false, default is "false")

Set to true

This semicolons to separate multiple SQL can be used for other bulk operations (delete, modify)

jdbc.url = jdbc:mysql://localhost:3306/mybatis_sgg?allowMultiQueries=true
    <!--这种方式需要数据库连接属性allowMultiQueries=true-->
    <insert id="addEmps">
      <foreach collection="emps" item="emp" separator=";">
          INSERT INTO tbl_employee(last_name,email,gender,d_id)
          VALUES (#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
      </foreach>
    </insert>

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/xjs1874704478/p/11896772.html