Introduction to Mybatis
MyBatis is an excellent persistence layer framework that supports plain SQL queries, stored procedures and advanced mapping. MyBatis eliminates manual settings of almost all JDBC code and parameters and search encapsulation of the result set. MyBatis can use simple XML or annotations for configuration and original mapping, mapping interfaces and Java's POJOs (Plain Old Java Objects) into records in the database.
Mybatis' functional architecture is divided into three layers (the picture is borrowed from Baidu Encyclopedia):
1) API interface layer: Provides interface APIs for external use, through which developers manipulate databases. Once the interface layer receives the call request, it will call the data processing layer to complete the specific data processing.
2) Data processing layer: Responsible for specific SQL search, SQL parsing, SQL execution and execution result mapping processing, etc. Its main purpose is to complete a database operation based on the request of the call.
3) Basic support layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading and cache processing. These are all common things, extracting them as the most basic components. Provides the most basic support for the upper layer of data processing layer.
When select mapping in MyBatis, the return type can be used with resultType or resultMap. resultType directly represents the return type, while resultMap is a reference to the external ResultMap, but resultType and resultMap cannot exist at the same time. When MyBatis is querying mapping, in fact, each attribute query is placed in a corresponding map, where the key is the attribute name and the value is its corresponding value. When the provided return type attribute is resultType, MyBatis will take out the key value pairs in the map and assign them to the corresponding attributes of the object specified by resultType. So in fact, the return type of each query map of MyBatis is a ResultMap. However, when the return type attribute we provide is resultType, MyBatis automatically assigns the corresponding value to the attributes of the object specified by resultType. When the return type we provide is resultMap, because the Map cannot represent the domain model well, we need to further convert it into the corresponding object ourselves, which is often very useful in complex queries.
There is 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;}public void setTitle(String title) {this.title = title;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getOwner() {return owner;}public void setOwner(String owner) {this.owner = owner;}public List<Comment> getComments() {return comments;}public void setComments(List<Comment> comments) {this.comments = comments;}@Overridepublic String toString() {return " ----------------博客-----------------/n id: " + id + "/n title: " + title + "/n content: " + content+ "/n owner: " + owner;}}The corresponding database table contains id, title, Content, and Owner attributes. When we perform the following query mapping
<typeAlias alias="Blog" type="com.tiantian.mybatis.model.Blog"/><!--Configuration file from MyBatis mybatis_config.xml--><select id="selectBlog" parameterType="int" resultType="Blog">select * from t_blog where id = #{id}</select><!--From SQL mapping file BlogMapper.xml-->MyBatis will automatically create a ResultMap object, and then encapsulate the key value pair based on the found attribute name. Then, you will see that the return type is a Blog object, and then take out the key value pair corresponding to the Blog object from the ResultMap and assign it.
It is also very useful when the return type is directly a ResultMap, which is mainly used for complex joint queries, because it is not necessary to conduct simple queries. Let's first look at a simple query with a return type ResultMap, and then look at the usage of complex queries.
How to write a simple query
<resultMap type="Blog" id="BlogResult"><id column="id" property="id"/><result column="title" property="title"/><result column="content" property="content"/><result column="owner" property="owner"/><result column="owner" property="owner"/><result column="owner" property="owner"/><result column="owner" property="owner"/><</resultMap><select id="selectBlog" parameterType="int" resultMap="BlogResult">select * from t_blog where id = #{id}</select>The value of resultMap in the select map is the id of an external resultMap, indicating which result is mapped to. The type attribute of the external resultMap indicates what type the result of the resultMap is. Here is the Blog type, so MyBatis will take it out as a Blog object. The child node id of the resultMap node is used to identify the id of the object, while the result child node is used to identify some simple properties. The Column property represents the attributes queried from the database, and the Property represents which property the corresponding value of the queryed property is assigned to the entity object. This is how to write resultMap for simple query. Next, let’s take a look at a more complicated query.
There is a Comment class, which has a Blog reference, indicating which Blog it is for. When querying Comment, we must also find out the corresponding Blog and assign it to its blog attribute.
import java.util.Date;public class Comment {private int id;private String content;private Date commentDate = new Date();public 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 ----------------评论-----------------/n id: " + id + "/n content: " + content + "/n commentDate: " + commentDate;}}It's written like this
<!--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_Comment where id = #{id}</select><select id="selectBlog" parameterType="int" resultType="Blog">select * from t_Blog where id = #{id}</select>The access situation is like this. First, you request the select map with the id of selectComment, and then you get a ResultMap object with the 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 there is no id and result child node corresponding to the simple query mentioned above, but it will still assign the corresponding id and other attributes to the Comment object. This is what MyB mentioned earlier. atis has automatic encapsulation function. As long as you provide a return type, MyBatis will use the query results to encapsulate the corresponding object according to its own judgment. Therefore, in the simple query above, if you do not explicitly point out which field corresponds to id and which field corresponds to title in the resultMap, MyBatis will also encapsulate it according to its own judgment. MyBatis's own judgment is to compare the field of the query or its corresponding alias with the attributes of the return object. If it matches and the type also matches, MyBatis will assign it. A blog attribute is associated in the corresponding resultMap above, and its corresponding JAVA type is Blog. In the above writing method, the associated object is associated through subqueries, and of course, it can also be associated directly through the association query. In the above association child node, the Property attribute indicates which associated property is the resultMap return type. For the example above, the blog attribute managed by Comment; select indicates which select map to map the corresponding associated attribute, that is, it will request a select map with the value corresponding to select to query the attribute object associated; Column indicates the key-value pair corresponding to the resultMap with id CommentResult. This key-value pair will be used as a parameter for the subquery of the associated object, that is, the value of the blog attribute query in selectComment is passed as a parameter to the subquery of the associated object blog to the subquery of the associated object blog; javaType indicates what type of the current associated object is in JAVA.
The above introduces a query of one-to-one or one-to-many relationship to one-party in the case of one-to-many. In actual applications, there is another application that uses more frequently. It is necessary to find out the corresponding more parties through one party. When taking out the more parties, one party must also be associated with one party. That is, in the above example, when taking out the Blog object, all the corresponding Comments are taken out. When taking out the Comment, it still needs to take out the corresponding Blog. This is taken out through a request in JAVA. The writing method 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><!-- Find Comment by Blog --><select id="selectCommentsByBlog" parameterType="int" resultMap="CommentResult">select * from t_comment where blog = #{blogId}</select>The entry of the above request is a select map with id selectBlog, and the return result is a resultMap with id BlogResult. The type of id BlogResult is Blog, which specifies the attributes and fields of id. Specifying id will have a great effect on the internal construction of MyBatis. It is associated with a comments object. Because a Blog can have many comments, which are a collection, so it is mapped with a collection collection. The select still indicates which subquery is performed to query the corresponding comments. column means which field value found above is passed to the subquery as a parameter. ofType also represents the return type. The return type here is the type inside the collection. The reason why ofType is used instead of type is that it is used within MyBatis to distinguish it from the association association.
Test code:
@Testpublic 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*/@Testpublic 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 brief overview of the resultMap in MyBatis introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!