Mybatis--mapper.xml Mapping File

Source: Internet
Author: User

Mapper.xml mapping File reprint: Http://loveshisong.cn/mybatis/2015/01/22/MyBatis (%e4%b8%89) mapper.xml%e6%98%a0%e5%b0%84%e6%96 %87%e4%bb%b6.html structure of this article
    • Introduction to SELECT statements
    • Introduction to insert Update Delete
    • Parameters parameters
    • Resultmap
Introduction to SELECT statements

The query statement is one of the most commonly used elements in MyBatis, first an example

<select id="selectPerson" parameterType="int" resultType="hashmap"> SELECT * FROM PERSON WHERE ID = #{id}</select>

Where the XXXType use of the fully qualified name or alias, where the symbol #{id} will use a preprocessing statement, in SQL will be a "?" To identify, in the JDBC equivalent of this:

// Similar JDBC code, NOT MyBatis…String selectPerson = "SELECT * FROM PERSON WHERE ID=?";PreparedStatement ps = conn.prepareStatement(selectPerson);ps.setInt(1,id);

selectElements also have many properties

Id|The unique identifier in the namespace,Can be used to refer to this statementResulttype|If this is a collection scenario,That should be the type that the collection can contain.,But not the collection itself..For example, the returned result is multiple persion,You should write persion instead of list here.Resultmap|Named references to external Resultmap,cannot be used in conjunction with Resulttype.I'll tell you later.ParameterType|Default value:unset.Options available,MyBatis can infer parameters for specific incoming statements through TypehandlerFlushcache|Default value:False.True indicates that any time the statement is called,Both local cache and level two cache will be emptied.UseCache|Default value:True.True indicates that the result of this statement is cached by level twoTimeout|Default:unset.Before throwing an exception,The number of seconds that the driver waits for the database to return request resultsResultsetType|Default:unset.Value is Forward_only,One of the scroll_sensitive or scroll_insensitiveFetchsize|Default:unset.The number of result rows returned by the driver for each batch is equal to the value of this settingStatementType|Default value:PREPARED.STATEMENT,A prepared or callable..This will allow MyBatis to use statement respectively.,PreparedStatement or CallableStatementDatabaseId|If you have configuredDatabaseidprovider, MyBatis will load all the statements without databaseid or matching the current DatabaseID ;  If you have a statement with or without , it will be ignored resultordered | Default value:false. This setting applies only to nested results SELECT statements: if true, the assumption is that nested result sets or groupings are included , so that when a main result row is returned ,  There is no case of a reference to the preceding result set . This makes not enough memory to be used when getting nested result sets resultsets | This setting applies only to multi-result sets , which list the result sets returned after the statement executes and each result set to a name , separated by commas        
Insert, update, and delete introduction

insert, update, deleteselectSimilarly, there are many attributes, which

    • id, parameterType, timeout, statementType, databaseIdSame as the attributes in the Select element;
    • flushCacheThe default value is ' true '
    • There are some insert和update properties that are unique, such as:
 usegeneratedkeys |  default value: falsekeyproperty |  default: unset uniquely marks an attribute , The MyBatis will  If you want to get multiple generated columns ,keycolumn | ,,       

For example, if your database supports fields that automatically generate primary keys (such as MySQL and SQL Server), you can set usegeneratedkeys= "true" and then set Keyproperty to the target property.

<insert id="insertAuthor" useGeneratedKeys="true" keyProperty="id"> insert into Author (username,password,email,bio) values (#{username},#{password},#{email},#{bio})</insert>
Parameters parameters

Parameters are MyBatis very powerful features, parameterType="anyType" which can be anyType int such as basic types, or can be User such complex types.

<insert id="insertUser" parameterType="User"> insert into users (id, username, password) values (#{id}, #{username}, #{password})</insert>

In the example above, the complex type that is passed in User will User look in the ID, username, and password attributes and put them in the corresponding location. If the int type is or is String not present, the value is placed directly in the corresponding position.

In addition, parameter mappings can specify a mapping type, or even a type processor, which can javaType often be inferred from a Parameter object, as previously said.

 #{age,javaType=int,jdbcType=NUMERIC,typeHandler=MyTypeHandler}
String substitution

By default, the syntax using the #{} format creates a preprocessing statement property and safely sets the value (for example,?). However, sometimes you just want to insert a non-changing string directly into the SQL statement, you can use parameters like this:

ORDER BY ${columnName}

This MyBatis does not modify or escape the string

Resultmap

resultMapThe element is the most important and powerful element in MyBatis, and the resultmap element itself has some attributes, which are the following code, which is used to id identify the resultMap type resultMap map to whichJavaBean

<resultMap id="blogResultMap" type="Blog">...</resultMap>

It also has a lot of child elements, the following is resultMap the concept map of the elements

Resultmap

    • constructor-classes are instantiated to inject results into the constructor method
      • Idarg-id parameters; Marking results as IDs can help improve overall performance
      • Arg-A common result injected into the constructor method
    • ID – an ID result; Marking results as IDs can help improve overall performance
    • result– normal results injected into a field or JavaBean property
    • association– a complex type association; many results will be wrapped into this type
      • Embed result mapping – the association of the result map itself, or refer to a
    • collection– sets of complex types
      • Embed result mapping – the set of the result map itself, or refer to a
    • discriminator– use result values to determine which result mapping to use
      • case– result mappings based on certain values
      • Embedded result mapping – The result of this scenario also maps itself, so it can contain many of the same elements, or it can refer to an external result map

Note Because of the limitations of the DTD, the order in which these elements appear must be in the order above

resultMapeach child element described in detail below

ID and result

This is the most basic content, the only difference between the two is that id the specified property will be a property that uniquely identifies the object, which can improve efficiency, especially when there is a federated mapping.
idand reslut elements have column, property, javaType, jdbcType, typeHandler attributes, which are column used to specify the column names in the database, property to specify JavaBean the corresponding properties, and the other properties are the same as they were previously said.

<id column="id" property="id"/><result column="user_name" property="username"/>
Construction Method Constructor

If the resultMap constructed method you are mapping JavaBean needs to provide a parameter, you constructor cannot lack the
constructorThere idArg are arg two sub-elements, the same meaning (see id and result the difference), are given to the construction method parameters. Their attributes are the same as the same id result
constructorThe usual forms are as follows:

<constructor>  <idArg column="id" javaType="int"/> <arg column="username" javaType="String"/></constructor>

Note that Java does not have a method for self-examination (reflection) parameter names, so make sure that the order of the parameters here is the same JavaBean as the defined order, and that the data type is also deterministic.

Association Association

The correlation element handles the "have one" type of relationship. For example, a blog has an author, just like this

From Author.javaPublicClassAuthor{PrivateIntegerId;private string nameprivate integer age}//from Blog.javapublic class  Blog {private integer idprivate string titleprivate string contentprivate author author//the corresponding field in the database is author_id int type               /span>                

You can do this. cascading queries

<resultmapId="Blogresultmap"Type="Blog"><idcolumn="id"property="id"/><resultcolumn="Title"property="Title"/><resultcolumn="Content"property="Content"/><!--as long as the return type is provided, such as the above ID and the field specified by result, even if the mybatis is not specified, it can be automatically encapsulated-<associationcolumn="AUTHOR_ID"property="Author"Javatype="Author"select= "Com.test.mybatis.mapper.AuthorMapper.selectAuthorById" /> <!--here if you have an alias you can also use--></resultmap> <select id= "Selectblogbyid" parametertype=  "int" resultmap= "Blogresultmap" > SELECT * From blog WHERE id = #{id}</select><!--from Authormapper.xml--><select id= "Selectauthorbyid" parametertype=  "int" resulttype= "Author" > select * FROM Author WHERE id = #{id}</SELECT>         

associationis passed to the select subquery by using the field specified by column as a parameter.

Set Collection

If the blog has a lot of comments, there will be a "one-to-many" situation, such as the above Blog will be an extra attribute

    //Blog.java新增的属性    private List<Comment> comments;//Comment.javapublic class Comment { private Integer id; private String content; private Blog blog; ...}

Then for Blog the query will become this

<resultmapId="Blogresultmap"Type="Blog"><idcolumn="id"property="id"/><resultcolumn="Title"property="Title"/><resultcolumn="Content"property="Content"/><!--as long as the return type is provided, such as the above ID and the field specified by result, even if the mybatis is not specified, it can be automatically encapsulated-<associationcolumn="AUTHOR_ID"property="Author"Javatype="Author"select="Com.test.mybatis.mapper.AuthorMapper.selectAuthorById"/><!--If an alias is used here, you can use the<collectionproperty="Comments"Javatype="ArrayList"column="id"Oftype="Comment"select="Com.test.mybatis.mapper.CommentMapper.selectCommentForBlog"/></resultMap><selectId="Selectblogbyid"Parametertype="Int"resultmap= "Blogresultmap" > select * FROM blog WHERE id = #{id}< Span class= "NT" ></select><!--from Authormapper.xml--><select id= "Selectauthorbyid" parametertype= "int" resulttype= "Author" > select * from Author WHERE id = #{id}</select><!--from Commentmapper.xml--><select id= "Selectcommentforblog" parametertype= "int" resulttype= "Comment" > select * from Comment WHERE blog_id = #{id}</SELECT>             

Which is ofType used to represent the type stored in the collection, which can be understood as producing one ArrayList<Comment> comments , the javaType property can be omitted, column the ID is specified as an incoming parameter

Mybatis--mapper.xml Mapping File

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.