我有一个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;
}
// ...
}
难点在于我想在列和embeddedId列的一部分之间建立OneToMany连接。 对这个问题有什么想法吗? (我正在使用hibernate 4.0.1)
答案 0 :(得分:7)
该位置必须使用@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;
}
// ...
}
这两个映射在the documentation中解释。