Hibernate @EmbeddedId + join

I have a problem displaying sleep mode. I have the following two DB tables (I am not allowed to modify the DB):

LOCATIONS { ID, -- PK NAME } LOCATION_GROUPS { LOC_ID, -- PK, and FK to LOCATIONS.ID GROUP_NAME -- PK } 

I tried to create entities for these database tables, but I do not know how to map the connection between the tables. Here is my attempt (but this is wrong):

 @Embeddable public class LocationGroupId implements Serializable { private static final long serialVersionUID = -6437671620548733621L; private Location loc; private String group; @Column(name = "LOC_ID") public Location getLoc() { return loc; } @Column(name = "GROUP_NAME") public String getGroup() { return group; } // ... } @Entity @Table(name = "LOCATION_GROUPS") public class LocationGroup { private LocationGroupId id; @EmbeddedId public LocationGroupId getId() { return id; } // ... } @Entity @Table(name = "LOCATIONS") public class Location { private Long id; private String name; private List<LocationGroup> groups; @Column(name = "NAME") public String getName() { return this.name; } @OneToMany(mappedBy = "id.loc") public List<LocationGroup> getGroups() { return this.groups; } @Id @Column(name = "ID") @SequenceGenerator(name = "LocationIdGen", sequenceName = "LOCATION_SQ") @GeneratedValue(strategy = GenerationType.AUTO, generator = "LocationIdGen") public Long getId() { return this.id; } // ... } 

The difficulty is that I want to make a OneToMany connection between the column and the embeddedId column part. Any idea on this issue? (I am using hibernate 4.0.1)

+3
mapping hibernate one-to-many
May 27 '13 at 14:09
source share
1 answer

The location should be mapped to @JoinColumn , not @Column :

 @JoinColumn(name = "LOC_ID") public Location getLoc() { return loc; } 

Please note that this is not a standard JPA. To make it standard you should use

 @Embeddable public class LocationGroupId implements Serializable { private static final long serialVersionUID = -6437671620548733621L; private Long locationId; private String group; @Column(name = "LOC_ID") public Long getLocationId() { return loc; } @Column(name = "GROUP_NAME") public String getGroup() { return group; } // ... } @Entity @Table(name = "LOCATION_GROUPS") public class LocationGroup { private LocationGroupId id; private Location location; @EmbeddedId public LocationGroupId getId() { return id; } @ManyToOne @JoinColumn(name = "LOC_ID") @MapsId("locationId") private Location getLocation() { return location; } // ... } 

These two mappings are explained in the documentation .

+4
May 27 '13 at 14:55
source share



All Articles