我有一個具有唯一名稱的實體。在唯一約束例外後保存實體
在我的例子中,我救了兩個同名的人。第二次出現「EntityExists」(唯一)異常,這是預期的行爲。
之後我改變了名稱,並將「ID」設置爲空。 比我試圖堅持下去,但我得到「org.apache.openjpa.persistence.EntityExistsException:嘗試堅持分離對象」[email protected]「。如果這是一個新的實例,請確保任何版本和/或堅持當自動生成主鍵字段爲空/默認
沒有它的工作版本,但我覺得沒有解決「復位」的版本號
有人可以幫助我
更新。?我的新問題是,我有一個基本實體兩個pcVersionInit(看我的答案在底部)我不能重寫它,我試過它在基礎和普通實體什麼現在是最佳做法,而不是「覆蓋」pcVersionInit中的值?拷貝構造函數「
public class Starter{
private static EntityManager em;
public static void main(String[] args) {
em = Persistence.createEntityManagerFactory("openjpa")
.createEntityManager();
Person p1 = new Person("TEST");
savePerson(p1);
Person p2 = null;
try{
p2 = new Person("TEST");
savePerson(p2);
}catch(Exception e){
p2.setId(null);
p2.setName(p2.getName()+"2");
em.persist(p2);
}
}
private static void savePerson(Person person){
em.getTransaction().begin();
em.persist(person);
em.getTransaction().commit();
}
}
Person.class:
@Entity
public class Person implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator="seqGenerator")
@SequenceGenerator(name="seqGenerator",sequenceName="personSeq")
private Long id;
@Version
private Long version;
@Column(nullable=true, unique=true)
private String name;
public Person(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}
謝謝你...... :) – pL4Gu33