MyBatis Database Statement Label

Source: Internet
Author: User

one. Update, insert return PRIMARY key

In fact, there are several kinds of problems, first put the online kind of a key, and then return to the entity class
Use the database Custom function nextval (' student ') to generate a key and set it to the StudentID attribute in the incoming entity class. After executing this method, assign the key to the StudentID property

 <insert id= "createstudent"  parametertype= "data.model.StudentEntity"  keyproperty=  "StudentID"  > <selectkey keyproperty= "StudentId"  resulttype= "string"  order  = "before"  > select  nextval ( ' student ')  </selectKey> INSERT into  student_tbl (student_                 ID, Student_sex, Student_photo) VALUES (#{studentid}, #{studentsex},  #{studentphoto, javatype=byte[], Jdbctype=blob, Typehandler=org.apache.iba Tis.type.BlobTypeHandler})  </insert>  

again, an ID is self-growing.
Here's the parameter I'm passing in the map.
Set usegeneratedkeys= "true" self-growth
keyproperty= "id" This ID is actually refers to the database since the growth of the field, after the insert is completed by default to fill him, after the completion of the map to take the corresponding key to get the value can be

<insert id="insertTaxiOrder"   parameterType="map" useGeneratedKeys="true"  keyProperty="ID" >       INSERT INTO  tb_TaxiOrderInfo ( UserID, DriverID, StartAddress)       VALUES  (#{userID}, 0, #{StartAdd}})    </insert>

Property Description Value
The 1.keyProperty Selectkey statement generates the properties that the result needs to be set.

2.resultType generates a result type, MyBatis allows the use of basic data types, including string, int, and map types.

3.order
3.1:before, the primary key is selected first, then the Keyproperty is set and the INSERT statement is executed;
3.2:after, run the INSERT statement before you run the Selectkey statement.

4.statementType MyBatis supports statement,prepared and callable statements, corresponding to statement, PreparedStatement, and CallableStatement responses

Two. Use of If

2.1 The parameter I passed in is in map form, in the SQL statement in Mapper, you can use if to determine if the parameter value is null, to see if the code block in the if is executed, the number is also possible

<SelectId="Registercyuser"Parametertype="Map"Resulttype="Map">SELECTWorkstaffid, ISNULL (PWD,") As PWD, Worktype         fromTb_workstaffWHEREWorktype =#{worktype}<iftest="Carnum! = null"> andCarnum =#{carnum}<iftest="Carnum = = null"> andCarnum =#{carnum}</if> </Select>

2.2 If a parameter is passed to an entity class, you can also judge

On the internet, just take it down here and judge it in the IF.

<SelectId="Studentlis"resultmap="Studentresult"Parametertype="model. Studententity ">SELECTSt. student_id, ST. Student_name, fromStudent_tbl STWHERE<iftest="Studentsex! = null and Studentsex! =" "> andSt. Student_sex =#{studentsex, Jdbctype=integer}</if> <iftest="Placeentity! = null and Placeentity.placeid! = null and Placeentity.placeid! =" "> andSt. place_id =#{placeentity.placeid, Jdbctype=varchar}</if> </Select>

2.3 If and set update updates using a combination

<update id="Updatezsinfo"Parametertype="Map"> UPDATE Tb_ordinaryuser <Set> <iftest="UserName! = null"> UserName =#{username},</if> <iftest="Phone! = null"> Phone =#{phone},</if> <iftest="Email! = null"> Email =#{email},</if> </Set>WHEREUserID =#{userid}</update>
three. Use of the TRIM keyword

3.1 Trim Alternative where

<select id="If_trim"resultmap="Studententity"> SELECTST. STUDENT_ID,ST. STUDENT_name, from Student_tblST<trim prefix="WHERE"prefixoverrides="And|or"> <if test="Studentname!=null">ST. STUDENT_name like CONCAT (CONCAT ('% ',#{studentname, Jdbctype=varchar}), '% ')</if> <if test="Studentsex! = null and Studentsex! =" "> and ST. STUDENT_sex =#{studentsex, Jdbctype=integer}</if> <if test="Studentbirthday! = null"> and ST. STUDENT_birthday =#{studentbirthday, jdbctype=date}</if> </trim> </select>

3.2 Trim instead of set

  <update id="Update_trim" parametertype= "studententity"> UPDATE STUDENT_TBL<trim prefix="SET" suffixoverrides=",">              <if test="studentname! = null and Studentname! =" ">Student_tbl. Student_name = #{studentname},</if>              <if test="studentsex! = null and Studentsex! =" ">Student_tbl. Student_sex = #{studentsex},</if>          </trim>WHERE Student_tbl. student_id = #{studentid}</Update>  
Four. Choose

4.1 Choose is a collection when and otherwise used

<!--6 Choose (judging parameters)-In order to successfully enter the first into when the execution of the statement as a where condition if not entered, will enter the otherwise to execute--  <select id="Choose" resultmap="studententity"  ParameterType="studententity">SELECT ST. student_id, ST. Student_name, from Student_tbl ST<where>          <Choose>              < when test="Studentname!=null">St. Student_name like CONCAT (CONCAT ('% ', #{studentname, Jdbctype=varchar}), '% ')</ when >              < when test="Studentbirthday! = null">and ST. Student_birthday = #{studentbirthday, jdbctype=date}</ when >              <otherwise>              </otherwise>          </Choose>      </where>    </Select>  
five. Foreach

This is much faster than doing it yourself in the external for loop.

There are three types of foreach, each of which is list,,map three

Item: The specific object in the loop body. Supports point path access for attributes, such as Item.age,item.info.details.
Description: The object in the list and array, which is value in the map.
This parameter is required.

Collection: To make a Foreach object, as an entry, the List

  <select id="foreach_array" resultMap="bb" parameterType="aa">      SELECT xx._ID,             xx._NAME,        FROM XXXX xx      WHERE xx._ID       IN        <foreach collection="array" item="classId"  open="(" separator="," close=")">          #{classId}       </foreach>    </select>

5.2 Mate in uses parameters to pass in a list

<select  id= " Countbyuserlist " resulttype=" _int " parametertype=  "list"  > select  count (*) from  users <where  > ID in
      <foreach  item= "item"  Collection= "list"  separator= open= "("  close= index= > #{item.id, jdbctype=numeric}  </foreach  > </  where  > </select  > 

5.3 Bulk Insert
Mode 1

     into aa ( depart1, depart2 ) values      <foreach collection="list" item="item" index="index"      separator=",">      #{item.depart1}, #{item.depart2} )      </foreach>

Mode 2

    insert into table(aa,bb)    <foreach collection="list" item="item" index="index" separator="union all">     select #{item.hkgs,aa=VARCHAR}, #{item.bb,jdbcType=VARCHAR},     } from dual    </foreach>

5.4 Bulk Delete

  <delete id="dd" parameterType="list">        in         item="item" index="index" collection="list"open="(" separator=","close=")">        #{item}        </foreach>  </delete>

5.5 Batch Modification

      <update id="update" parameterType="list">          set‘0‘wherein          <foreach collection="list" item="nos" open="(" separator="," close=")">           #{nos}         </foreach>         </update>

5.6 Batch Condition Query

<select id="sel" resultType="int">          select count(*) from aa  where          <foreach item="item"index="key" collection="map"              open="" separator="AND"close="">            ${key}#{item}</foreach>      </select> 

$ {} is output as-is, #{} is a value

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

MyBatis Database Statement Label

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.