gpt4 book ai didi

Hibernate @EmbeddedId + join

转载 作者:行者123 更新时间:2023-12-03 07:01:38 25 4
gpt4 key购买 nike

我有一个 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;
}

// ...
}

使用了EmbeddedId

    @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 连接。对这个问题有什么想法吗? (我使用的是hibernate 4.0.1)

最佳答案

该位置必须使用 @JoinColumn 进行映射,而不是使用 @Column:

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

请注意,这不是标准 JPA。为了使其成为标准,您可以使用

可嵌入类

@Embeddable
public class LocationGroupId implements Serializable {

private static final long serialVersionUID = -6437671620548733621 L;
private Long locationId;
private String group;

@Column(name = "LOC_ID")
public Long getLocationId() {
return loc;
}

@Column(name = "GROUP_NAME")
public String getGroup() {
return group;
}
// ...
}

已使用嵌入式Id

@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中进行了解释。 .

关于Hibernate @EmbeddedId + join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16775055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com