I have the following entities:
____________________ ____________________
| Activity | | Benefit |
------------------ | |------------------|
| activityId:long |-------------| benefitId: long |
| activity:varchar | | activityId: long |
| .... | | benefit: varchar |
-------------------- -------------------|
Can I map this into Hibernate so I end up with this:
@Entity
class Activity {
@Id
private Long id;
private String activity;
private List<String> benefits;
}
Yes, you can use the @ElementCollection
tag.
Here's what your code would look like:
@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;
}
Though I would call the table ActivitiesBenefits
instead of Benefit
to make it clear that that table will store pairs of activities and benefits. Also, there is no need for a benefitId
, since a benefit is a weak entity (it cannot exist without an activity), so you can drop that too.
Reference: https://en.wikibooks.org/wiki/Java_Persistence/ElementCollection
Hi I could find one way in which you could do it. Below is code for same.
@Entity
@Table(name = "Activity")
class Activity {
@Id
@Column(name="activity_id")
private Long id;
@Column(name = "name")
private String activity;
@OneToMany
@Formula("(select CONCAT(benefitId, activityId, benefit) from Benefit b where b.activityId = activity_id)")
private List<String> benefits;
}
I am using a sql returning list of benefits and then concatenate it and store it in our benefits list. The string in formula is SQL(not HQL) so its column names and not filed member names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With