Some tips for configuring MyBatis and mybatis

Source: Internet
Author: User

Some tips for configuring MyBatis and mybatis
MyBatis alias configuration -- typeAliases

A type alias is a short name for the Java type. It is only related to XML configuration. It can only be used to reduce the redundancy of fully qualified classes. To put it bluntly, we need to set the package name in advance.

The api is written in this way.

<typeAliases>  <typeAlias alias="Author" type="domain.blog.Author"/>  <typeAlias alias="Blog" type="domain.blog.Blog"/></typeAliases>

You can also specify a package name. MyBatis searches for the required Java Bean under the package name, for example:

<typeAliases>  <package name="domain.blog"/></typeAliases>

 

This can be set directly under <configuration> in xml. aliases can be directly used when you use it again. However, there is a sequential relationship when writing it in xml! Solve the problem by yourself and adjust the location.

The corresponding type alias has been built into many common Java types. They are case-insensitive. Note that special processing is caused by duplicate basic type names.

Alias Ing type
_ Byte Byte
_ Long Long
_ Short Short
_ Int Int
_ Integer Int
_ Double Double
_ Float Float
_ Boolean Boolean
String String
Byte Byte
Long Long
Short Short
Int Integer
Integer Integer
Double Double
Float Float
Boolean Boolean
Date Date
Decimal BigDecimal
Bigdecimal BigDecimal
Object Object
Map Map
Hashmap HashMap
List List
Arraylist ArrayList
Collection Collection
Iterator Iterator
-- Mappers

 

Since MyBatis has been configured by the above elements, we need to define the SQL ing statement now. But first, we need to tell MyBatis where to find these statements. Java does not provide a good method for automatic search, so the best way is to tell MyBatis where to find the ing file. You can use a resource reference relative to the class path or a fully qualified resource locator (includingFile :///Or class name and package name.

There are four methods

<Mapper resource = "com/entity/UserMapper. xml "/> second, the local address is provided directly, and the address is stored by yourself. The resource locator is fully limited. <mapper url =" file: // var/mappers/UserMapper. xml "/> the third method is to search for <mapper class =" com. entity. authorMapper "/> fourth form of package name <package name =" com. entity. builder "/>

 

Ing configuration details

 

ResultMap and resultType  

When querying select ing in MyBatis, you can use resultType or resultMap for the return type,

  ResultTypeIt directly indicates the return type. Each queried attribute is placed in a corresponding Map. The key is the attribute name and the value is the corresponding value. When the returned type attribute is resultType, MyBatis extracts the key-value pairs in the Map and assigns them to the attributes of the object specified by resultType. In fact, the returned type of each query ing in MyBatis is ResultMap, but when the returned type attribute we provide is resultType, myBatis automatically assigns the corresponding value to the attribute of the object specified by resultType.

  ResultMapIt is a reference to the external ResultMap, and then encapsulates the key-value pairs based on the searched attribute names. It is mainly used for complex joint queries. Result set ing is the most powerful feature of MyBatis. Many complex mappings can be easily solved.

The resultType and resultMap cannot exist at the same time.

Support inheritance of resultMap

  

Extends = "User" indicates that the previous resultMap is inherited. If an entity class is very heavy, it is a good choice to give a framework that everyone inherits from.

<! -- Multi-to-Multi-join query --> <resultMap id = "User" type = "com. entity. user "> <result property =" id "column =" id "/> <result property =" username "column =" username "/> <result property =" password "column = "password"/> </resultMap> <resultMap id = "user_info" type = "User" extends = "User"> <collection property = "userInfos" ofType = "com. entity. userInfo "column =" uid "> <result property =" id "column =" id "/> <result property =" address "column =" address "/> </collection> </resultMap> <select id = "getUser" resultMap = "user_info"> select * from user u, userinfo I where u. id = I. uid and u. id = # {id} </select>
Multi-condition query with dynamic SQL statements If

A dynamic SQL statement is usually used to include a where clause conditionally.

<select id="findActiveBlogWithTitleLike"     resultType="Blog">  SELECT * FROM BLOG   WHERE state = ‘ACTIVE’   <if test="title != null">    AND title like #{title}  </if></select>

This statement provides an optional text search type. If "title" is not input, all blogs in the "ACTIVE" status will be returned.

Choose
<select id="queryEmp"  resultType="cn.test.entity.Emp">          select * from emp where 1=1          <choose>          <when test="deptNo!=null">          and deptno=#{deptNo}          </when>          <when test="deptName!=null">          and deptname=#{deptName}          </when>          <otherwise>          and personnum>#{personNum}          </otherwise>          </choose>

</select>

As mentioned above, choose is equivalent to the switch statement in Java. when the first when satisfies, only the conditions in the first when are executed. When none of the conditions in the when are met, the default statement is executed, that is, the statement in otherwise.

Where
<select id="getU" resultMap="User" parameterType="com.entity.User">        select*from user        <where>            <if test="username!=null and username!=''">                username like concat('%',#{username},'%')            </if>            <if test="id!=null">                and id=#{id}            </if>        </where>    </select>

In where, the first if statement starts with and can also omit the first and. if the first if statement contains and; mybatis, the first and is ignored.

Set
<update id="updateEmp" parameterType="cn.test.entity.Emp" flushCache="true">          update emp           <set>          <if test="empName!=null">empname=#{empName},</if>          <if test="job!=null">job=#{job}</if>          </set>          where empno=#{empNo}          </update>

";" Cannot be added at the end of the SQL statement in mybatis, which will cause mybatis to be unable to recognize characters and cause syntax errors of the SQL statement;

Foreach

Another common operation required for dynamic SQL is to traverse a set, usually when constructing an IN Condition Statement.

<select id="selectPostIn" resultType="domain.blog.Post">  SELECT *  FROM POST P  WHERE ID in  <foreach item="item" index="index" collection="list"      open="(" separator="," close=")">        #{item}  </foreach></select>

The foreach element is very powerful. It allows you to specify a set and declare the set items and index variables that can be used in the element body. It also allows you to specify the string that matches the open/closed condition and place the Separator in the middle of the iteration. This element is intelligent, so it does not accidentally add additional delimiters.

 

 

[Version Declaration] This article is an original article by the blogger. For more information, see the source.

 

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.