JPA EntityManager.persist方法拋異常的原因
阿新 • • 發佈:2020-07-29
當主鍵生成策略設定為手動設定:new出來的物件設定好 id 才能 persist,否則拋異常
@Test public void test() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("myJpa"); EntityManager em = factory.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); Student s = new Student(); s.setSname("張飛"); s.setSage(21); em.persist(s); /* javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): cn.wm.domain.Student */ tx.commit(); em.close(); factory.close(); }
@Entity public class Student { @Id // 沒有新增@GeneratedValue註解,即手動設定主鍵 private Long sid; private String sname; private Integer sage; public Long getSid() { return sid; } public void setSid(Long sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public Integer getSage() { return sage; } public void setSage(Integer sage) { this.sage = sage; } @Override public String toString() { return "Student{" + "sid=" + sid + ", sname='" + sname + '\'' + ", sage=" + sage + '}'; } }
當主鍵生成策略設定為自動生成:new出來的物件 id 必須為 null 才能 persist ,否則拋異常
@Test public void test() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("myJpa"); EntityManager em = factory.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); Student s = new Student(); s.setSid(1L); s.setSname("曹操"); s.setSage(26); em.persist(s); /* javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: cn.wm.domain.Student */ tx.commit(); em.close(); factory.close(); }
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // 設定主鍵生成策略設定為自動生成
private Long sid;
private String sname;
private Integer sage;
public Long getSid() {
return sid;
}
public void setSid(Long sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Integer getSage() {
return sage;
}
public void setSage(Integer sage) {
this.sage = sage;
}
}