我有一个hibernate映射问题。我有以下两个数据库表(不允许更改数据库):
LOCATIONS { ID, -- PK NAME } LOCATION_GROUPS { LOC_ID, -- PK, and FK to LOCATIONS.ID GROUP_NAME -- PK }
我试图为这些数据库表创建实体,但是我不知道如何映射表之间的连接。这是我的尝试(但这是错误的):
@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; } // ... }
困难在于我想在列和一部分嵌入式Id列之间建立一个OneToMany连接。对这个问题有想法吗?(我正在使用hibernate4.0.1)
必须使用@JoinColumn而不是使用来映射位置@Column:
@JoinColumn
@Column
@JoinColumn(name = "LOC_ID") public Location getLoc() { return loc; }
请注意,虽然这不是标准的JPA。要使其成为标准,您将使用
@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; } // ... }
在文档中解释了这两个映射。