Reputation: 673
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?
Upvotes: 0
Views: 131
Reputation: 2890
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;
Upvotes: 1