您好,我有一个任务,我想保存一些ParentObject,但是此ParentObject与表上的PK有关于childrenObject的关系。但是根据我的逻辑,我没有仅PK的业务密钥(代码)。还有一个问题,当我只有业务密钥(代码)时,如何用此childrenObject的FK保存parenObject。 (业务密钥与子表中的PK一样唯一)。
我可以通过按业务密钥获取childrenTable,然后更新PK巫婆与parentObject相关来手动完成此操作。但是我认为这很愚蠢,我希望Hibernate可以为我做这件事。
代码:
@Entity
@Table(name = "parent_object")
public class ParenObject {
@Id
private Integer id;
@NaturalId
@Column(name = "code", unique = true, nullable = false)
private String code;
@Column(name = "name", unique = true, nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "children_id")
private ChildrenObject childrenObject;
}
@Entity
@Table(name = "children_object")
public class ChildrenObject {
@Id
private Integer id;
@NaturalId
@Column(name = "code", unique = true, nullable = false)
private String code;
@Column(name = "name", unique = true, nullable = false)
private String name;
}
使用CRUD存储库,我只想简单地保存该对象:
{ "id": null,
"code": "12345",
"name": "Parent Entity",
"childrenObject": {
"id":null,
"code":"09876",
"name": "Children Entity"
}
}
答案 0 :(得分:0)
不幸的是,您似乎必须首先获取它。如The best way to map a @NaturalId business key with JPA and Hibernate中所述:
Hibernate已经有了一个完善的逻辑,可以根据持久性上下文中的标识符加载和关联实体。
,似乎存储对象也是如此,并且Hibernate严重依赖@Id
列。即使要使用其自然标识符加载实体,它也会首先执行查询以获取实际的@Id
,然后进行第二次查询以获取实体本身(基于同一篇文章的示例):
SELECT c.id AS id1_0_
FROM ChildrenObject c
WHERE c.code = 'child-code'
SELECT c.id AS id1_0_0_,
c.code AS code2_0_0_,
c.name AS name3_0_0_
FROM ChildrenObject c
WHERE c.id = 1