zoukankan      html  css  js  c++  java
  • MyBatis多表映射demo

    三个实体类,作者、文章和评论。
    
    public class Author {
        private int id;
        private String username;
        private String nickname;
        private LocalDate birthday;
        private LocalDateTime registerTime;
    }
     
    public class Article {
        private int id;
        private String title;
        private String content;
        private Author author;
        private List<Comment> comments;
        private LocalDateTime createTime;
        private LocalDateTime modifyTime;
    }
     
    public class Comment {
        private int id;
        private String content;
        private Author author;
        private Article article;
        private LocalDateTime createTime;
    }
    

      

    相应的数据表如下:
    
    CREATE TABLE author (
      id            INT AUTO_INCREMENT PRIMARY KEY,
      username      VARCHAR(255) NOT NULL  UNIQUE,
      nickname      VARCHAR(255),
      birthday      DATE,
      register_time DATETIME     NOT NULL
     
    );
    CREATE TABLE article (
      id          INT AUTO_INCREMENT PRIMARY KEY,
      title       VARCHAR(255) NOT NULL,
      content     TEXT         NOT NULL,
      author      INT          NOT NULL,
      create_time DATETIME     NOT NULL,
      modify_time DATETIME     NOT NULL,
      FOREIGN KEY (author) REFERENCES author (id)
     
    );
    CREATE TABLE comment (
      id          INT AUTO_INCREMENT PRIMARY KEY,
      author      INT      NOT NULL,
      article     INT      NOT NULL,
      content     TINYTEXT NOT NULL,
      create_time DATETIME NOT NULL,
      FOREIGN KEY (author) REFERENCES author (id),
      FOREIGN KEY (article) REFERENCES article (id)
    );
    

      

    映射结果

    在前面的例子中,由于是简单的一对一单表映射,所以直接使用resultType属性指定需要映射的结果。

    但是如果是复杂的例子,或者列名和属性名不对应,那么这种情况就不行了。这时候需要改为使用另一个属性resultMap来映射结果。

    resultMap属性需要指定一个resultMap的ID。在resultMap中我们需要指定结果的映射,如果列名和属性名相同的话还可以省略映射。id用于映射主键,result用于映射其他属性。

    <!--查询作者-->
    <select id="selectAuthor" resultMap="authorResult">
        SELECT
            id,
            username,
            nickname,
            birthday,
            register_time
        FROM author
        WHERE id = #{id}
    </select>
    <!--作者结果映射-->
    <resultMap id="authorResult" type="Author">
        <id property="id" column="id"/>
        <result property="registerTime" column="register_time"/>
    </resultMap>
    

      

    结果的关联

    上面的例子演示了如何使用resultMap。下面我们来看看如何关联结果。假设我们现在要查询文章,由于文章表中有一个作者的外键,文章实体类也有作者的引用。因此简单的查询在这里并不适用。我们需要使用关联来将文章和作者关联起来,有两种方式:嵌套查询关联和嵌套结果关联。

    嵌套查询关联

    这是一种非常简单的方式,非常易于理解。嵌套查询关联需要使用association元素,并指定select属性。select属性指定另一个查询的ID,MyBatis会在每一条记录上使用该查询再执行一次嵌套查询以获取结果。

    <!--查询文章-->
    <select id="selectArticle" resultMap="articleMap">
        SELECT
            id,
            title,
            content,
            author,
            create_time,
            modify_time
        FROM article
        WHERE id = #{id}
    </select>
    <!--嵌套查询关联文章表-->
    <resultMap id="articleMap" type="Article">
        <id property="id" column="id"/>
        <result property="createTime" column="create_time"/>
        <result property="modifyTime" column="modify_time"/>
        <association property="author" column="author" select="selectAuthor"/>
    </resultMap>
    
    但是这种方式有一个问题,就是著名的N+1问题。我们要获得一些文章,需要执行一条SQL语句(这就是1),然后对于每条文章,我们还得执行一次查询来获得作者的信息(这就是N)。在查询数据量较大的时候会显著影响性能。为了避免这个问题,我们需要使用下面的方式:嵌套结果关联。
    
    嵌套结果关联
    
    嵌套结果关联其实就是我们在编写SQL语句的时候直接编写多表查询。如果有重名的列我们可以考虑添加前缀来解决名称冲突问题。需要注意这次我们在association元素添加的不是select属性了。而是resultMap属性。因为文章表和作者表存在重名属性,所以我们需要在SQL语句中使用as子句修改列名,同时使用columnPrefix="a_"来指定列前缀。这样MyBatis才能正确识别。
    
    另外一个需要注意的地方是默认情况下MyBatis的autoMappingBehavior是PARTIAL,也就是说MyBatis会自动映射单表属性,但是遇到这种关联结果就不会自动映射。因此我们在确认没有重复名称之后就可以手动设置autoMapping="true",覆盖MyBatis的全局配置。一般情况下autoMappingBehavior的值不要指定为FULL,除非你确定所有表的所有字段不会出现重复。在我们这个例子中,如果去掉表前缀并让MyBatis自动映射所有字段,你会发现作者ID和文章ID会被错误的设置为同一个ID。
    
    <select id="selectArticle" resultMap="articleMap">
        SELECT
            article.id,
            title,
            content,
            author,
            create_time,
            modify_time,
            author.id     AS a_id,
            username      AS a_username,
            nickname      AS a_nickname,
            birthday      AS a_birthday,
            register_time AS a_register_time
        FROM article, author
        WHERE article.id = #{id} AND author.id = article.author
    </select>
    <!--嵌套查询关联文章表-->
    <resultMap id="articleMap" type="Article" autoMapping="true">
        <id property="id" column="id"/>
        <result property="createTime" column="create_time"/>
        <result property="modifyTime" column="modify_time"/>
        <association property="author" column="author"
                     resultMap="authorMap" columnPrefix="a_"/>
    </resultMap>
    
    我们可以看到嵌套结果比嵌套查询要复杂很多。这是为了性能而不得已的折中方案。另外在结果映射中最好显式指定主键,由于主键可以唯一标识行,能让MyBatis以更好的性能来映射结果。
    
    结果的集合
    
    有时候一个实体类会包含另一个实体类的集合。例如上面的文章类包含了一个评论集合。这时候就需要另外一种方式将集合映射到结果了。
    
    嵌套查询集合
    
    嵌套查询集合和嵌套查询关联非常类似,只不过把association元素改为collection元素即可。和嵌套查询关联一样,嵌套查询集合也有N+1性能问题。在数据量大的时候最好不要使用。
    
    在嵌套查询集合中,需要额外添加一个属性ofType,指定结果中元素的类型。对于每一条记录,MyBatis会调用指定的查询,查询出一个集合,并传给要映射的类型。
    
    <!--嵌套查询关联文章表-->
    <resultMap id="articleMap" type="Article" autoMapping="true">
        <result property="createTime" column="create_time"/>
        <result property="modifyTime" column="modify_time"/>
        <collection property="comments" column="id"
                    ofType="Comment" select="selectCommentsByArticle"/>
    </resultMap>
    <!--查找评论-->
    <select id="selectCommentsByArticle"
            resultMap="commentMap">
        SELECT
            id,
            content,
            create_time
        FROM comment
        WHERE article = #{id}
    </select>
    <resultMap id="commentMap" type="Comment" autoMapping="true">
        <id property="id" column="id"/>
        <result property="createTime" column="create_time"/>
    </resultMap>
    
    嵌套结果集合
    
    嵌套结果集合和嵌套结果关联类似。但是由于这次不是一对一的关联映射,而是一对多的集合映射。所以我们只能使用外连接来编写SQL语句。同样的,为了区分重名的行,我们需要添加列前缀。另外评论类还有几个外键,这里为了简便就不进行查询和映射了。如果再添加外键的映射,SQL语句就会变得更长。
    
    <select id="selectArticle" resultMap="articleMap">
        SELECT
            article.id,
            title,
            article.content,
            article.author,
            article.create_time,
            modify_time,
            comment.id          AS c_id,
            comment.content     AS c_content,
            comment.create_time AS c_create_time
        FROM article
            LEFT JOIN comment ON article.id = comment.article
        WHERE article.id = #{id}
    </select>
    <!--嵌套查询关联文章表-->
    <resultMap id="articleMap" type="Article" autoMapping="true">
        <id property="id" column="id"/>
        <result property="createTime" column="create_time"/>
        <result property="modifyTime" column="modify_time"/>
        <collection property="comments" column="id"
                    ofType="Comment" resultMap="commentMap"
                    columnPrefix="c_"/>
    </resultMap>
    
    MyBatis中最麻烦的地方就是这些映射了。在编写映射的时候我们必须非常小心,最好使用单元测试来帮助我们一步一步核对映射的正确性。
    
    测试一下
    
    前面介绍了单表映射,关联映射,集合映射等几种映射方式。下面我们来看看MyBatis文档中的一个例子。这是一个很长的SQL语句和相应的结果映射。如果你完全看懂了,就说明你已经完全掌握了MyBatis最核心最重要的功能了。
    
    <!-- Very Complex Statement -->
    <select id="selectBlogDetails" resultMap="detailedBlogResultMap">
      select
           B.id as blog_id,
           B.title as blog_title,
           B.author_id as blog_author_id,
           A.id as author_id,
           A.username as author_username,
           A.password as author_password,
           A.email as author_email,
           A.bio as author_bio,
           A.favourite_section as author_favourite_section,
           P.id as post_id,
           P.blog_id as post_blog_id,
           P.author_id as post_author_id,
           P.created_on as post_created_on,
           P.section as post_section,
           P.subject as post_subject,
           P.draft as draft,
           P.body as post_body,
           C.id as comment_id,
           C.post_id as comment_post_id,
           C.name as comment_name,
           C.comment as comment_text,
           T.id as tag_id,
           T.name as tag_name
      from Blog B
           left outer join Author A on B.author_id = A.id
           left outer join Post P on B.id = P.blog_id
           left outer join Comment C on P.id = C.post_id
           left outer join Post_Tag PT on PT.post_id = P.id
           left outer join Tag T on PT.tag_id = T.id
      where B.id = #{id}
    </select>
    
    对应的映射文件。
    
    <!-- Very Complex Result Map -->
    <resultMap id="detailedBlogResultMap" type="Blog">
      <constructor>
        <idArg column="blog_id" javaType="int"/>
      </constructor>
      <result property="title" column="blog_title"/>
      <association property="author" javaType="Author">
        <id property="id" column="author_id"/>
        <result property="username" column="author_username"/>
        <result property="password" column="author_password"/>
        <result property="email" column="author_email"/>
        <result property="bio" column="author_bio"/>
        <result property="favouriteSection" column="author_favourite_section"/>
      </association>
      <collection property="posts" ofType="Post">
        <id property="id" column="post_id"/>
        <result property="subject" column="post_subject"/>
        <association property="author" javaType="Author"/>
        <collection property="comments" ofType="Comment">
          <id property="id" column="comment_id"/>
        </collection>
        <collection property="tags" ofType="Tag" >
          <id property="id" column="tag_id"/>
        </collection>
      </collection>
    </resultMap>
    

      

  • 相关阅读:
    回顾
    单例模式
    元类
    反射和内置方法
    issubclass 和 isinstance和断点调试
    绑定方法和非绑定方法
    并发编程:IO多路复用。
    基于tcp的下载文件,以及struct模块的应用。
    并发编程:协程,异步调用。
    并发编程:GIL,线程池,进程池,阻塞,非阻塞,同步,异步
  • 原文地址:https://www.cnblogs.com/ipetergo/p/6807622.html
Copyright © 2011-2022 走看看