Mybatis Result Maps is used to group results.

Source: Internet
Author: User

Mybatis Result Maps is used to group results.

Reprinted Please note:TheViper http://www.cnblogs.com/TheViper 

One-to-multiple relationships, such as articles and comments, must be displayed and grouped by articles. Most of the time, only the number of comments is displayed on the page. If you want to view a specific comment, you need to click the link of the number of comments.

For example, Weibo

Zhihu

What should I do if I want to display the first few comments when presenting an article (or Weibo? (Mongodb is not discussed here)

A common practice is to retrieve the peer and multiple external connections and then traverse the group manually.

Here we will take the article comments and replies as an example.

Comment table

Reply table

The id fields of the two tables indicate the user id of the comment and the user id of the reply. The comment_id of the articlereplay table is a foreign key. There is also a user table (id, name ).

External Connection

        SELECT articlecomment.articlecomment_id,articlecomment.commenttime,articlecomment.commentcontent,articlecomment.id as commentuser_id        ,articlereply.articlereply_id,articlereply.replytime,articlereply.replycontent,articlereply.id as replyuser_id        ,u1.name AS comment_user,u2.name AS reply_user FROM articlecomment         LEFT JOIN articlereply ON articlereply.comment_id=articlecomment.articlecomment_id INNER JOIN USER AS u1 ON u1.id=articlecomment.id         INNER JOIN USER AS u2 ON u2.id=articlereply.id ORDER BY commenttime DESC,replytime DESC    

In fact, you do not need to write code to traverse the results and group them. Using the resultmap of mybatis can help us to group by comment elegantly.

ArticleComment class

public class ArticleComment {    private int articlecomment_id;    private String commentcontent;    private String commenttime;    private User user;    private Article article;    private List<ArticleReply> replys;        //getter,setter  }

ArticleReply class

public class ArticleReply {    private int articlereply_id;    private String replycontent;    private String replytime;    private User user;        //setter,getter}

Resultmap

    <resultMap id="ArticleCommentResult" type="ArticleComment">        <id property="articlecomment_id" column="articlecomment_id" />        <association property="user" javaType="User">               <id property="id" column="commentuser_id"/>            <result property="name" column="comment_user"/>        </association>        <collection property="replys" ofType="ArticleReply">            <association property="user" javaType="User">                <id property="id" column="replyuser_id" />                <result property="name" column="reply_user"/>            </association>        </collection>    </resultMap>

Get "many" (articlereply) from the "1" (articlecomment) side. Note that <association> should be placed before <collection>; otherwise, an error is reported.

Org. apache. ibatis. builder. builderException: Error creating document instance. cause: org. xml. sax. SAXParseException; lineNumber: 16; columnNumber: 14; the content of the element type "resultMap" must match "(constructor ?, Id *, result *, association *, collection *, discriminator ?) ".

The category name of pojo should be the same as the field name of the corresponding table in the database. For more information, see mybatis3 autoMappingBehavior in this document.

In addition, the two tables are connected to the User table to obtain the User name. Therefore, the SQL statements are renamed as comment_user and reply_user.id. Here, rename it to commentuser_id and replyuser_id. This requires <result> adjustment to match the renamed field with the attribute name of the pojo class.

Effect

Again, the above shows all replies. The actual requirement may be that only five replies closest to the current time are selected. If you want to see more replies, click "load more ". What should I do?

See how to select the first, last, and first rows of each group in SQL.

        SELECT articlecomment.*,articlereply1.* FROM articlecomment         LEFT JOIN         (SELECT *        FROM articlereply        WHERE (               SELECT COUNT(*) FROM articlereply AS f               WHERE f.comment_id = articlereply.comment_id AND f.replytime >= articlereply.replytime              ) <= 2         ) AS articlereply1         ON articlereply1.comment_id=articlecomment.articlecomment_id ORDER BY articlereply1.replytime DESC

Left join a subquery. From the articlereply table, select the two replies closest to the current world in each group. The other replies are the same as those in the previous outer join query.

In addition, how to select the first/last/first rows of each group in SQLUser variablesThe method is to write the left join and articlereply subqueries in the preceding SQL statement as user variables. But there is a problem, the row_number in each group will increase sequentially, and what we need is order by replytime desc, which is opposite to the order of row_number.

Result

The preceding query does not filter row_number. If WHERE x. row_number <= 2, the result is the opposite.

At this time, it is easy to think of the Inverse Order of row_number, but Ben doesn't know how to modify if (@ type = type, @ num + 1, 1 ). There is no way to use subqueries.

SELECT *FROM (   SELECT articlereply.*,      @num := IF(@type =comment_id, @num + 1, 1) AS row_number,      @type := comment_id AS dummy   FROM articlereply ) AS X WHERE x.row_number>=(SELECT COUNT(*) FROM articlereply WHERE articlereply.comment_id=x.comment_id  GROUP BY articlereply.comment_id)-1

Result

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.