Hibernate:单个表中的多个@ManyToMany关系

时间:2017-04-04 18:34:18

标签: java sql hibernate jpa

我有一个项目,其中Hibernate用于管理实体。两个表之间可以存在多个@ManyToMany关系。所以基本上我有这样的代码:

@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "movies_screenplay_authors",
        joinColumns = @JoinColumn(name = "movie_id", nullable = false, updatable = false),
        inverseJoinColumns = @JoinColumn(name = "staff_id", nullable = false, updatable = false))
private Set<Staff> screenplayAuthors = Sets.newHashSet();

@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "movies_story_authors",
        joinColumns = @JoinColumn(name = "movie_id", nullable = false, updatable = false),
        inverseJoinColumns = @JoinColumn(name = "staff_id", nullable = false, updatable = false))
private Set<Staff> storyAuthors = Sets.newHashSet();

现在,我想将这些关系存储在单个表中,并附加一些描述关系类型的列。所以基本上,我想有这样的东西(使用伪代码):

@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "movies_staff",
        joinColumns = @JoinColumn(name = "movie_id", nullable = false, updatable = false),
        inverseJoinColumns = @JoinColumn(name = "staff_id", nullable = false, updatable = false),
        joinCriteria = @JoinCriteria(columnName = "staff_type", value = StaffType.SCREENPLAY_AUTHOR, enumType = EnumType.STRING))
private Set<Staff> screenplayAuthors = Sets.newHashSet();

@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "movies_staff",
        joinColumns = @JoinColumn(name = "movie_id", nullable = false, updatable = false),
        inverseJoinColumns = @JoinColumn(name = "staff_id", nullable = false, updatable = false),
        joinCriteria = @JoinCriteria(columnName = "staff_type", value = StaffType.STORY_AUTHOR, enumType = EnumType.STRING))
private Set<Staff> storyAuthors = Sets.newHashSet();

这在Hibernate或Java世界的任何地方都可能吗?

1 个答案:

答案 0 :(得分:0)

您可以在每个@JoinTable注释后添加如下内容:

@Fetch(FetchMode.SUBSELECT)

及其全部。