[英]JPA/Hibernate OneToOne association, persist call inserts entity with null Id
[英]Hibernate persist error, id field is null
大家好,我試圖做一個持久性,但看起來好像從未設置屬性之一,但是在持久性之前,我打印了值並已設置。 我正在與postgrest合作
我堅持的方法
public void saveText(Document document){
sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
System.out.println(document.getText());
System.out.println(document.getId());
try {
session.beginTransaction();
session.persist(document);
session.getTransaction().commit();
}
catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
}
我對悲觀主義者的反對
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import br.com.symsar.sysged.acessobd.AccesData;
@Entity
@ManagedBean
@SessionScoped
@Table(name = "documents", schema = "public")
public class Document implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "\"id\"")
private int id;
@Column(name = "\"text\"")
private String text;
public void persist() {
AccesData access = new AccesData();
access.saveText(this);
}
/**
* @return the text
*/
public String getText() {
return text;
}
/**
* @param text
* the text to set
*/
public void setText(String text) {
this.text = text;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
休眠顯示的SQL查詢
Hibernate: insert into public.documents ("id", "text") values (null, ?)
這是錯誤:
ERROR: ERRO: Null value in the column "id" violates not-null constraint
字段id
在您的實體類中具有JPA批注@Id
。 這意味着它不能為null
。 嘗試插入不帶id參數的值:
Hibernate: insert into public.documents ("text") values (?)
嘗試刪除注釋@ManagedBean @SessionScoped
當我使更改生效時,我決定不使用會話工廠,而現在使用實體管理器。 謝謝大家的想法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.