gpt4 book ai didi

java - 在 Hibernate 实体中使主键与外键相同

转载 作者:行者123 更新时间:2023-12-02 19:32:40 26 4
gpt4 key购买 nike

我是 Hibernate 新手。我正在研究以下两个实体:

实体 1 如下:

@Entity
@Table(name = "vm_user")
public class VmUser implements Serializable {

private static final long serialVersionUID = 1L;

@Column(name = "created_by")
private String createdBy;

@Column(name = "last_modified_by")
private String lastModifiedBy;

@Column(name = "created_date")
private Instant createdDate;

@Column(name = "last_modified_date")
private Instant lastModifiedDate;

@OneToOne
@JoinColumn(unique = true)
private User user; <--- HOW WILL I DENOTE THIS PRIMARY KEY OF VMUSER ENTITY ?

在mysql的关联表中,即vm_useruser_id既是主键,也是外键,引用user表的id与 User 实体关联。

实体 2 如下:

@Entity
@Table(name = "my_entity")
public class MyEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Column(name = "created_by")
private String createdBy;

@Column(name = "last_modified_by")
private String lastModifiedBy;

@Column(name = "created_date")
private Instant createdDate;

@Column(name = "last_modified_date")
private Instant lastModifiedDate;

@ManyToOne
private A a;

@OneToOne
@JoinColumn(unique = true)
private B b;

在mysql的关联表中,即my_entity,主键是id of aid of b的组合。我不知道如何在 Hibernate 实体 MyEntity 中表示这一点。

关于同样的事情,我浏览了几篇文章:Hibernate foreign key as part of primary keyJPA & Hibernate - Composite primary key with foreign key ,但不知道如何做这两个?

最佳答案

解决方案是@MapsId

例如

@Entity
@Table(name = "vm_user")
public class VmUser implements Serializable {

@Id
@Column(name = "user_id")
private Integer id;

@MapsId
@OneToOne
private User user;

您还可以删除 @JoinColumn(unique = true),因为 @Id 已使其成为唯一的。

public class MyEntityPk implements Serializable {

private Integer aId;
private Integer bId;

// IMPORTANT: Override equals() and hashCode()
}


@IdClass(MyEntityPk.class)
@Entity
@Table(name = "my_entity")
public class MyEntity implements Serializable {

@Id
private Integer aId;
@Id
private Integer bId;

@MapsId("aId")
@ManyToOne
private A a;

@MapsId("bId")
@OneToOne
private B b;

请在 Hibernate 文档 https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#identifiers-derived 中查找更多信息

关于java - 在 Hibernate 实体中使主键与外键相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61555425/

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