我有两个班A,B。
这是Main类:
public class Main
{
static PersistenceManagerFactory pmf ;
static Transaction tx1 ;
static PersistenceManager pm1 ;
public Main(){
pmf = JDOHelper.getPersistenceManagerFactory("datanucleus.properties");
}
public static void testB(B b){
pm1 = pmf.getPersistenceManager();
tx1=pm1.currentTransaction();
try {
tx1.begin();
B bb=b;
pm1.makePersistent(bb);
tx1.commit();
} finally {
if (tx1.isActive())
{
tx1.rollback();
}
pm1.close();
}
}
public static void main(String args[]) {
Main n=new Main();
String id="4";
A a=new A(id,"prova");
B b2=new B("4a",a);
B b3=new B("5a",a); //// error HERE ////////////////////////////////
Main.testB(b2);
Main.testB(b3);
}
}当我运行主类时,会得到一个错误,即:
Exception in thread "main" javax.jdo.JDODataStoreException: Insert of object "B@95973d" using statement "INSERT INTO `B` (`ID`,`IDR`) VALUES (?,?)" failed : Duplicate entry '4' for key 'PRIMARY'
at org.datanucleus.api.jdo.NucleusJDOHelper.getJDOExceptionForNucleusException(NucleusJDOHelper.java:421)
at org.datanucleus.api.jdo.JDOPersistenceManager.jdoMakePersistent(JDOPersistenceManager.java:735)
at org.datanucleus.api.jdo.JDOPersistenceManager.makePersistent(JDOPersistenceManager.java:755)
at Main.testB(Main.java:167)
at Main.main(Main.java:322)据我理解,在主类中,特别是在这一行代码中:
A a=new A(id,"prova");
B b2=new B("4a",a);
B b3=new B("5a",a); //// error HERE ////////////////////////////////
Main.testB(b2);
Main.testB(b3);我得到错误“重复条目'4‘的关键字’主'”
在表B中,我想为表A的PK插入多个值,如何修复它?
发布于 2014-02-24 16:40:32
因此,当您持久化B时,"A“对象处于”瞬态“状态,因此它每次都会尝试持久化一个新的A。如果您将A持久化,然后分离 it (pm.detachCopy,当对象标记为可拆卸时),并将B的A字段设置为该字段,则它将工作。任何JDO文档都有对分离和对象状态的引用。像这样创造A
pm.currentTransaction().begin();
A a = new A(id,"prova");
a = pm.makePersistent(a);
A detachedA = pm.detachCopy(a);
pm.currentTransaction().commit();然后使用"detachedA“和B的持久化。
https://stackoverflow.com/questions/21993064
复制相似问题