java Mybatis多对多最佳实践

kknvjkwl  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(198)

成员表:

id int  
name varchar

俱乐部桌:

id int  
name varchar

会员和俱乐部索引表:

member_id int  
club_id int  
register_date timestamp

如果我想通过id查询一个有俱乐部的会员,以及每个俱乐部的注册时间,我应该如何设计POJO,我应该把索引表Map到一个实体上,这个实体包含member和club的引用吗?还是有更好的做法?

hgncfbus

hgncfbus1#

下面是我推荐的对象模型:

class Member {
    Integer id;
    String name;
    List<ClubRegistration> clubRegistrations;
}

class Club {
    Integer id;
    String name;
    List<MemberRegistration> memberRegistrations;
}

class ClubRegistration {
    Club club;
    Date date;
}

class MemberRegistration {
    Member member;
    Date date;
}

以便您可以通过两种方式获取数据:会员与其俱乐部或俱乐部与其会员。
SQL查询:

SELECT m.id AS memberId, m.name AS memberName, c.id AS clubId, c.name AS clubName, register_Date
FROM member m
         INNER JOIN member_club mc ON m.id = mc.member_id
         INNER JOIN club c ON mc.club_id = c.id
WHERE {what you want}

您所问案例的ResultMap:

<resultMap id="memberRM" type="Member">
  <id column="memberId" property="id"/>
  <result column="memberName" property="name"/>
  <collection property="clubRegistrations" ofType="ClubRegistration">
    <result column="register_Date" property="date" />
    <association property="club" javaType="Club">
      <id column="clubId" property="id"/>
      <result column="clubName" property="name"/>
    </association>
  </collection>
</resultMap>

只需将会员/俱乐部换成另一个案例即可。
然后,您甚至应该引用resultMap而不是nest define:

<association property="club" resultMap="clubRM" />

虽然我没有亲自检查过the circular reference issue that would arise is managed bay MyBatis

相关问题