休眠同一实体的多个@manytomy关联

dgiusagp  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(328)

我有以下场景:
我有一个实体叫做 MyOtherEntity 具有类型属性的。 MyEntity 只与某些 MyOtherEntity 基于类型的实体 MyOtherEntity . MyEntity 类(仅用于演示未正确建模):

@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` 班级:

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

private String type;

// more fields

}

更详细的示例:
假设只有3种类型的 `MyOtherEntity` 类型1、类型2和类型3。我的目标是 `MyEntity` 与 `MyOtherEntity` 类型1和类型2的实体。
使用hibernate可以实现这个功能吗?
ctehm74n

ctehm74n1#

您可以使用@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;

相关问题