Mybatis多对多最佳做法

时间:2017-02-09 10:05:32

标签: java mybatis

会员表:
id int
name varchar

俱乐部桌子:
id int
name varchar

会员和俱乐部索引表:
member_id int
club_id int
register_date时间戳

如果我想通过id和俱乐部查询会员以及每个俱乐部的注册时间,我应该如何设计POJO。我应该将索引表映射到包含会员和俱乐部参考的实体吗?或者有更好的做法?

1 个答案:

答案 0 :(得分:2)

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

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