![](/img/trans.png)
[英]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.