简体   繁体   中英

Hibernate multiple @ManyToMany associations to the same entity

I have the following scenario:

I have an entity called MyOtherEntity that has a type attribute. MyEntity is associated only with certain MyOtherEntity entities based on the type of MyOtherEntity .

MyEntity class (only for demonstration it's not modelled correctly):

@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:

@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. My goal is to only associate MyEntity with MyOtherEntity entities of type1 and type2.

Is this functionality possible to achieve using Hibernate?

You can use @Where annotation.

@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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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