Jdo错误重复键

时间:2014-02-24 16:17:07

标签: java jdo

我有2个班级A,B。

这是主要课程:

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);
    }
}

当我运行Main类时,我收到一个错误,即:

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)

据我了解,在Main类中,特别是在这行代码中:

    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'用于键'PRIMARY'”

在表B中,我想为表A的PK插入多个值,我该如何解决?

1 个答案:

答案 0 :(得分:1)

因此,当你持久存在B时,“A”对象处于“瞬态”状态,因此每次都会尝试持久保存新的A.相反,你坚持A然后分离它(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的持久性。