Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi valued attribute in Hibernate

Tags:

java

hibernate

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;
}
like image 359
MichelReap Avatar asked Sep 05 '25 03:09

MichelReap


2 Answers

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

like image 184
Hector Ricardo Avatar answered Sep 07 '25 18:09

Hector Ricardo


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.

like image 40
Viraj Nalawade Avatar answered Sep 07 '25 16:09

Viraj Nalawade