A brief overview of Resultmap in MyBatis _java

Source: Internet
Author: User

MyBatis Introduction

MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures, and advanced mappings. MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval encapsulation of the result set. MyBatis can use simple XML or annotations for configuration and raw mappings, mapping interfaces and Java Pojo (Plain old Java Objects, normal Java objects) to records in the database.

MyBatis's functional architecture is divided into three layers (Pictures borrowed from Baidu Encyclopedia):

1 API Interface layer: provided to external use interface API, developers through these local APIs to manipulate the database. When the interface layer receives the call request, it invokes the data processing layer to complete the specific data processing.

2 Data Processing layer: Responsible for specific SQL lookup, SQL parsing, SQL execution and execution result mapping processing. Its main purpose is to complete a database operation based on the call request.

3 Basic Support Layer: responsible for the most basic function support, including connection management, transaction management, configuration loading and caching processing, these are common things, they are extracted as the most basic components. Provide the most basic support for the upper layer of data processing.

In MyBatis, the return type can be resulttype for a select mapping in a query, or the return type can be directly represented by Resultmap,resulttype, whereas Resultmap is a reference to an external resultmap. But Resulttype and Resultmap cannot exist at the same time. In MyBatis query mapping, in fact, every query out of the attributes are placed in a corresponding map inside, where the key is the property name, the value is its corresponding value. When the provided return type attribute is Resulttype, MyBatis assigns the key value in the map to the property of the object specified by Resulttype. So in fact, the return type of each query map in MyBatis is Resultmap, but when the return type attribute we provide is Resulttype, mybatis the property that automatically assigns the corresponding value to the object specified by Resulttype. And when we provide the return type is Resultmap, because the map does not represent the domain model well, we need to translate it further into the corresponding object, which is often useful in complex queries.

Have such a Blog.java file

 import java.util.List; public class Blog {private int id; private String title; private
String content;

Private String owner;
Private list<comment> comments; public int getId () {return id;} public void setId (int id) {this.id = ID;} public String GetTitle () {return title;} p ublic void Settitle (string title) {this.title = title; public string GetContent () {return content;} public void Setco Ntent (String content) {this.content = content;} public string GetOwner () {return owner.} public void SetOwner (String o

Wner) {This.owner = owner;}

Public list<comment> getcomments () {return comments;} public void Setcomments (list<comment> comments) {this.comments = comments;} @Override public String toString () {R Eturn "----------------blog-----------------\ n ID:" + id + "\ n Title:" + title + "\ n content:" + content + "\ Owner:"
+ owner; }
}

The Id,title,content,owner attribute is stored in the corresponding database table, so when we do the following query mapping

<typealias alias= "Blog" type= "Com.tiantian.mybatis.model.Blog"/><!--from MyBatis profile mybatis_config.xml-- >
<select id= "Selectblog" parametertype= "int" resulttype= "Blog" >
select * from t_blog where id = #{id}< c3/></select><!--from SQL map file blogmapper.xml-->

MyBatis automatically creates a Resultmap object and then encapsulates the key-value pair based on the lookup property name, and then sees the return type as a blog object, and then takes out the key-value pairs of the blog object from the Resultmap to assign the value.

It is also useful when the return type is directly a resultmap, mainly for complex federated queries because it is not necessary to make simple queries. Let's take a look at a simple query with a return type of Resultmap, and then look at the use of complex queries.

The writing of a simple query

<resultmap type= "Blog" id= "Blogresult" > <id "column=" id "property="
id "/> <result column=
" Title "property=" title "/>
<result column=" content "property=" content "/> <result"
owner " property= "owner"/>
</resultMap>
<select id= "Selectblog" parametertype= "int" resultmap= " Blogresult ">
select * from t_blog where id = #{id}
</select>

The value of the Resultmap in the Select map is the ID of an external resultmap that indicates which resultmap the returned result maps to, and the Type property of the outer resultmap indicates what type of the resultmap result is. Here is the blog type, then MyBatis will take it as a blog object out. The child node ID of the RESULTMAP node is used to identify the ID of the object, and the result child node is used to identify some simple properties, where the Column property represents the properties queried from the database. Property represents the property of the entity object to which the value of the queried attribute is assigned. This is how the resultmap of a simple query is written. Next, look at a more complex query.

There is a comment class, which has a blog reference, which is the comment of the blog, then we query comment when the corresponding blog will also be found to assign its blog properties.

Import java.util.Date;
public class Comment {
private int id;
Private String content;
Private date Commentdate = new Date ();
Private blog blog;
public int getId () {return
ID;
}
public void setId (int id) {
this.id = ID;
}
Public String getcontent () {return
content;
}
public void SetContent (String content) {
this.content = content;
}
Public Date Getcommentdate () {return
commentdate;
}
public void Setcommentdate (Date commentdate) {
this.commentdate = commentdate;
}
Public blog Getblog () {return
blog;
}
public void Setblog (blog blog) {
this.blog = blog;
}
Public String toString () {return
blog + "\ n----------------comment-----------------\ n ID:" + id + "\ n content:" + cont ent + "\ commentdate:" + commentdate;
}
}

That's how it's written.

 <!--from Commentmapper.xml file--> <resultmap type= "Comment" id= "Commentresult" > <association property= "blog" select= "Selectblog" column= "blog" javatype= "blog"/> </resultMap> < Select Id= "selectcomment" parametertype= "int" resultmap= "Commentresult" > select * from t_comment where id = #{id} </ select> <select id= "Selectblog" parametertype= "int" resulttype= "Blog" > select * from t_blog where id = #{id} < /select> 

Its access is the case, first a select mapping with the request ID selectcomment, and then a Resultmap object with an ID of commentresult. We can see that the return type of the corresponding Resultmap is a Comment object, which has only one association node, and does not have the Id,result child node corresponding to the simple query as described earlier. But it will still be the corresponding ID and other attributes to the comment object, which is said earlier MyBatis have automatic encapsulation function, as long as you provide the return type, MyBatis will be based on their own judgment to use the results of the query to encapsulate the corresponding object, so the simple query in the front, If you do not explicitly indicate in the Resultmap which field the ID corresponds to, which field the title corresponds to, MyBatis will also be based on its own judgment to help you encapsulate, MyBatis's own judgment is to query the field or its corresponding alias and return object properties are compared, If a match is matched and the type matches, MyBatis assigns the value to it. The corresponding resultmap in the above is associated with a blog attribute, its corresponding Java type for the blog, in the above writing, the association object is through the subquery to be associated, of course, can also directly through the association query. In the association node above, the property attribute represents which association property of the Resultmap return type, and for the above example is the blog attribute of comment management; Select represents which select map to map the corresponding associated property. The select map of the value corresponding to the request ID is queried to query for the Property object it is associated with; column represents the key-value pair of the current associated object in the Resultmap with ID Commentresult, which is used as a parameter to the subquery for the associated object , the value of the blog attribute queried in Selectcomment is passed as the parameter to the subquery Selectblog of the associated object blog; Javatype indicates what type of current associated object is in Java.

The above description is a one-to-one or one-to-many case, on one side of the associated query. In the actual application there is a more use of the application is through one side to identify the corresponding multiple side, in the case of more than one side to the same party, that is, in the above example, when the object of the blog to take out the corresponding comment all out, In the time to take out the comment also need to take out its corresponding blog, this is in Java in a request to take out. The wording is as follows:

<!--from blogmapper.xml file-->
<resultmap type= "Blog" id= "Blogresult" >
<id column= "id" property= "id"/>
<collection property= "Comments" select= "Selectcommentsbyblog" column= "id" oftype= "Comment" > </collection>
</resultMap>
<resultmap type= "Comment" id= "Commentresult" >
< Association property= "Blog" javatype= "blog" column= "blog" select= "Selectblog"/>
</resultMap>
< Select Id= "Selectblog" parametertype= "int" resultmap= "Blogresult" >
select * from t_blog where id = #{id}
</select>
<!--to find comment-->
<select id= "Selectcommentsbyblog" parametertype= "int" via blog resultmap= "Commentresult" >
select * from t_comment where blog = #{blogid}
</select>

The entry for the above request is a select map with ID Selectblog, which returns the resultmap,id with the ID of Blogresult as the type of Blogresult, which specifies the attribute and field of the ID. Specifying IDs will have a very large effect on the MYBATIS internal structure. A comments object is associated with it, because a blog can have a lot of comment, the comments is a collection, so it is mapped with a collection collection, where the select still indicates which subquery to query for the corresponding comments. column indicates which field value is passed as a parameter to the subquery, and OfType also represents the return type, where the return type is the type within the collection, and the reason why the oftype rather than the type is mybatis internal for the purpose of distinguishing it from the associated association.

Test code:

@Test public
void Selectcommentsbyblogtest () {
sqlsession session = Util.getsqlsessionfactory (). Opensession ( );
Commentmapper commentmapper = Session.getmapper (commentmapper.class);
List<comment> comments = Commentmapper.selectcommentsbyblog (6);
for (Comment comment:comments)
System.out.println (Comment);
Session.close ();
}
/**
* Query a single record * *
@Test public
void Testselectone () {
sqlsession session = Util.getsqlsessionfactory (). Opensession ();
Blogmapper blogmapper = Session.getmapper (blogmapper.class);
Blog blog = blogmapper.selectblog (6);
List<comment> comments = blog.getcomments ();
if (comments!= null) {
System.out.println ("--------------comments Size------------" + comments.size ());
for (Comment comment:comments)
System.out.println (Comment);
}
Session.close ();
}

The above is a small set to introduce the MyBatis in the Resultmap brief overview, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.