我有以下实体:
____________________ ____________________
| Activity | | Benefit |
------------------ | |------------------|
| activityId:long |-------------| benefitId: long |
| activity:varchar | | activityId: long |
| .... | | benefit: varchar |
-------------------- -------------------|
我可以将其映射到Hibernate中吗,所以我得到以下结果:
@Entity
class Activity {
@Id
private Long id;
private String activity;
private List<String> benefits;
}
最佳答案
是的,您可以使用@ElementCollection
标记。
您的代码如下所示:
@Entity
@Table(name = "Activity")
class Activity {
@Id
@Column(name="activity_id")
private Long id;
@Column(name = "name")
private String activity;
@ElementCollection
@CollectionTable(
name = "Benefit",
joinColumns = @JoinColumn(name = "activityId")
)
private List<String> benefits;
}
尽管我将表称为
ActivitiesBenefits
而不是Benefit
来明确表示该表将存储 Activity 和收益对。此外,由于福利是一个弱实体(没有 Activity 就无法存在),因此不需要benefitId
,因此您也可以删除它。参考:https://en.wikibooks.org/wiki/Java_Persistence/ElementCollection
关于java - Hibernate中的多值属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29496177/