简体   繁体   English

Hibernate 多个@ManyToMany 关联到同一个实体

[英]Hibernate multiple @ManyToMany associations to the same entity

I have the following scenario:我有以下情况:

I have an entity called MyOtherEntity that has a type attribute.我有一个名为MyOtherEntity的实体,它有一个 type 属性。 MyEntity is associated only with certain MyOtherEntity entities based on the type of MyOtherEntity . MyEntity仅与基于MyOtherEntity类型的某些MyOtherEntity实体相关联。

MyEntity class (only for demonstration it's not modelled correctly): MyEntity class(仅用于演示,未正确建模):

@Data
@Entity
@Table(name = "my_table")
public class MyEntity {

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
        name = "my_entity_my_other_entity_type1",
        joinColumns = {@JoinColumn(name = "my_entity_id")},
        inverseJoinColumns = {@JoinColumn(name = "my_other_entity_id")}
    )
    private List<MyOtherEntity> myOtherEntityType1;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
        name = "my_entity_my_other_entity_type2",
        joinColumns = {@JoinColumn(name = "my_entity_id")},
        inverseJoinColumns = {@JoinColumn(name = "my_other_entity_id")}
    )
    private List<MyOtherEntity> myOtherEntityType2;

    // more fields
}

MyOtherEntity class: MyOtherEntity class:

@Data
@Entity
@Table(name = "my_other_entity")
public class MyOtherEntity {

    private String type;

    // more fields
}

A more detailed example:一个更详细的例子:

Let's say there are only 3 types of MyOtherEntity type1, type2, and type3.假设只有 3 种类型的MyOtherEntity ,type1、type2 和 type3。 My goal is to only associate MyEntity with MyOtherEntity entities of type1 and type2.我的目标是仅MyEntity与 type1 和 type2 的MyOtherEntity实体相关联。

Is this functionality possible to achieve using Hibernate?使用 Hibernate 是否可以实现此功能?

You can use @Where annotation.您可以使用@Where 注释。

@Where(clause = "type = 'tyep1'")
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
    name = "my_entity_my_other_entity_type1",
    joinColumns = {@JoinColumn(name = "my_entity_id")},
    inverseJoinColumns = {@JoinColumn(name = "my_other_entity_id")}
)
private List<MyOtherEntity> myOtherEntityType1;

@Where(clause = "type = 'tyep2'")
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
    name = "my_entity_my_other_entity_type2",
    joinColumns = {@JoinColumn(name = "my_entity_id")},
    inverseJoinColumns = {@JoinColumn(name = "my_other_entity_id")}
)
private List<MyOtherEntity> myOtherEntityType2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM