[英]Hibernate: How to cascade embedded objects with parent object's auto-generated ID as a foreign key
[英]How to set an @Id primary key that is NOT Auto-Generated in Java JPA/Hibernate?
我將 Postgres 與 Java JPA/Hibernate 一起使用,並希望將 id 字段作為我手動生成的字段。 即每當我創建這個 object 的實例時,我都會設置 id 字段。
我已經嘗試了數周,但一直遇到:“找不到類所需的標識符屬性”或“保存后,標識符不能為空”。
這是我正在使用的 model class 的示例:
import javax.persistence.*;
@Entity
@Table(name = "pojo")
public class Pojo {
@Id
@Column(name = "id_one")
private int idOne;
@Column(name = "bool_example")
private boolean boolExample;
public Pojo(){};
public Pojo(int idOne, boolean boolExample){
this.idOne = idOne;
this.boolExample = boolExample;
}
public int getIdOne() {
return idOne;
}
public void setIdOne(int idOne) {
this.idOne = idOne;
}
public boolean isBoolExample() {
return boolExample;
}
public void setBoolExample(boolean boolExample) {
this.boolExample = boolExample;
}
}
這是我正在調用的示例請求
@GetMapping(value = "/plswork")
public String pojotestone(){
Pojo newpojo = new Pojo(1, false);
pojoService.saveThis(newpojo);
pojoService.test();
return "yes";
}
pojoService 調用 pojoRepository.save(T entity)。 這個 pojoRepository 來自 CrudRepository 的擴展,因此它可以動態創建查詢
對於所有想知道的人,
是 - 可以有一個手動 id,這在實體具有固有 id 屬性的多個用例中是有意義的。 (如信用卡、銀行賬戶等)
至於這個問題,原來是與Spring JDBC不兼容。 解決方案是使用 spring-boot-starter-data-jpa 代替,並讓存儲庫擴展 JPARepository 而不是 CrudRepository。
在 Spring Data JDBC( https://docs.spring.io/spring-data/jdbc/docs/2.2.12/reference/html/#is-new-state-detection )中有兩種方法可以做到這一點和 Spring 數據 JPA( https://docs.spring.io/spring-data/jpa/docs/2.7.7/reference/html/#jpa.entity-persistence.saving-entites.strategies )。 最直接的是實現Persistable<YourIdType
接口:
@Entity
@Table(name = "pojo")
public class Pojo implements Persistable<Integer>{
@Id
@Column(name = "id_one")
private int idOne;
@Column(name = "bool_example")
private boolean boolExample;
@Transient
private boolean isNew;
public setIsNew(boolean isNew) {
this.isNew = isNew;
}
@Override
public boolean isNew() {
return isNew;
}
//getters/setters/constructors...
}
現在如果你想保存一個新實體,id 設置為 Java,你只需要調用
pojo.setNew(true);
repository.save(pojo);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.