[英]JPA + Spring: Mapping a foreign key column to a ID based on the value received before persisting the entity
[英]Get generated entity Id before persisting, Hibernate, Spring data
一些先決條件:
我沒有使用 Oracle DB 序列生成器。 而不是它,我依賴於 Hibernate 序列生成器 ex
@Entity
@Table(name = "JPA_ENTITY_A")
@GenericGenerator(name = "system-uuid", strategy = "uuid2")
public class JpaEntityA{
@Id
@Type(type = "uuid-binary")
@GeneratedValue(generator = "system-uuid")
private UUID id;
@Column(name="NAME_WITH_ID")
String nameWithGeneratedId;
}
我想要的是將以下生成的值保存到“NAME_WITH_ID”列中: this.nameWithGeneratedId+this.id
執行以下操作是否可行:
public String getNameWithGeneratedId(){
return this.nameWithGeneratedId+this.id;//hope that the returned value will be persisted
}
或者是否可以在將實體持久化到數據庫生成的 id 之前提前檢索? 如果是,那么我該如何完成呢? (根據下面的評論,這是不可能的)
提前謝謝。
你不能; 持久化本身的行為是創建 ID 的原因。
在您使用 UUID 生成器的情況下,我認為您可以使用Lifecycle接口並實現返回NO_VETO
的onSave
方法。
例如
@Entity
public MyEntity implements Lifecycle {
@Id
@GeneratedValue
private UUID id;
...
public boolean onSave(final Session session) throws CallbackException {
// here your entity will have an ID
return Lifecycle.NO_VETO;
}
...
}
onSave
方法將在保存實體之前和生成 ID 之后調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.