【发布时间】:2021-02-25 02:28:27
【问题描述】:
我有一个实体类,它使用从数据库 (PostgreSQL) 自动生成的 id。它一直很好,不需要我为其指定一个 ID。例如
@Entity public class MyEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
// ... other columns
}
现在我想添加一个由该实体类拥有的具有单向关联的关联实体列表。例如
@Entity public class MyEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToMany(cascade = CascadeType.ALL) @JoinColumn(name="pid")
private List<SubEntity> subEntities;
// ... other columns
}
@Entity public class SubEntity implements Serializable {
@Id private Integer pid; // refer to id of MyEntity
@Id private String name; // pid, name forms a composite key for SubEntity
// ... other columns
}
然后我遇到了一个问题,即 JPA(在本例中为 Hibernate)正在生成如下 SQL:
INSERT INTO MYENTITY (...) VALUES (...)
INSERT INTO SUBENTITY (pid, ...) VALUES (null, ...)
尝试向 pid 插入空值时失败,因为它在数据库模式中没有空约束。如果我绕过这个,Hibernate 会生成一条更新语句,用 MyEntity 生成的 id 更新 null 值:
UPDATE SUBENTITY SET pid = ? WHERE pid = null AND name = ?
我知道自动生成的 id 直到插入到 MyEntity 之后才知道,所以它会在之后更新。但我想知道是否有一种解决方案,让 Hibernate 仅首先插入 MyEntity,获取生成的 id,然后使用正确的 pid 插入 SubEntity,之后不更新?
【问题讨论】:
-
你用的是什么休眠版本?