mybatis的關聯查詢以及count


1.多表查詢,1對1的時候,最簡單的做法

<resultMap id="postInfo" type="postInfoEntity">
        <id property="postId" column="post_id"/>
        <result property="userName" column="user_name"/>
        <result property="postTitle" column="post_title"/>
        <result property="postContent" column="post_content"/>
        <result property="topPost" column="top_post"/>
        <result property="wonderfulPost" column="wonderful_post"/>
        <result property="createTime" column="create_time"/>
        <result property="count" column="num"/>
    </resultMap>

    <!--某個貼吧所有界面的帖子,通過置頂降序排序-->
    <select id="listAllPostInfos" resultMap="postInfo">
        SELECT A.post_id, COUNT(*) num, post_title, post_content, top_post, wonderful_post, user_name, A.create_time
        FROM post_info A, nf_user B, reply_post_info C
        WHERE post_status = 1 AND C.reply_status = 1
        AND post_bar_id = #{param1}
        AND A.user_id = B.user_id
        AND A.post_id = C.post_id
        GROUP BY post_id
        ORDER BY top_post DESC, create_time
    </select>

其中COUNT(*) 取了一個別名,目的是為了對應resultMap中的<result property="count" column="num"/>, 然而僅僅這樣是不夠的,因為雖然查得到,但是mybatis映射不出來,他底層的反射和動態代理還需要我們在實體類進行設置——我們加一個屬性和property對應就可以了

 

@Data
@Document(indexName = "post_info")
public class PostInfoEntity {

    @Id
    private Long postId;
    @Field(type = FieldType.Long)
    private Long postBarId;
    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String postTitle;
    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String postContent;
    @Field(type = FieldType.Long)
    private Long userId;
    @Field(type = FieldType.Long)
    private Long topPost;
    @Field(type = FieldType.Long)
    private Long wonderfulPost;
    @Field(type = FieldType.Integer)
    private Integer audit;
    @Field(type = FieldType.Long)
    private Long visitCount;
    @Field(type = FieldType.Integer)
    private Integer postStatus;
    @Field(type = FieldType.Date)
    private Date createTime;
    private Integer count;
    private String userName;

}
// 除了@Data注解其他都無視,其他的是elasticsearch的

 

2.多表聯合查詢,可以像我們上面一樣,和COUNT(*)同一種寫法,直接寫一個<result>標簽然后實體類加一個屬性對應。就是上面的userName.

但是實際上我們多表的時候一般每一張表都有POJO類的,也可以把String userName改成NfUser nfUser  然后mapper中對應修改成<result properties="nfUser.userName" colum="user_name"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM