加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – JPA错误:持久关系时出现重复键错误

发布时间:2020-12-15 02:24:40 所属栏目:Java 来源:网络整理
导读:你好 我正在使用JPA来保存一些 java类,如下所示.只要数据库不包含具有与Y.x.id相同id的类X的元素,Y的持久性似乎工作正常.我为此感到困惑.似乎我正在使用的JPA实现( EclipseLink)似乎没有弄清楚虽然Y是新的,但Y.x并不是新的,即Y应该被持久化但是关系项X应该被
你好
我正在使用JPA来保存一些 java类,如下所示.只要数据库不包含具有与Y.x.id相同id的类X的元素,Y的持久性似乎工作正常.我为此感到困惑.似乎我正在使用的JPA实现( EclipseLink)似乎没有弄清楚虽然Y是新的,但Y.x并不是新的,即Y应该被持久化但是关系项X应该被更新.任何有助于弄清楚是什么导致这种情况的帮助将不胜感激.
如果有什么不清楚的话,我已经引用了我的程序源代码的相关摘要,请不要犹豫,请我澄清一下.

谢谢
提前.

public static interface YY {
    Object id();
}
@Entity
@Access(AccessType.FIELD)
@Table(name = "X")
public class X implements YY {

    @Id
    long id;

    protected X() {
        this.id = Test.orderId++;
    }


    @Override
    public Long id() {
        return id;
    }
    }

public class YPK {


    private final Date date;
    private final Long x;

    public YPK(X x,Date date) {
        this.date = date;
        this.x = x.id();
    }

    @Override
    public boolean equals(Object arg0) {
        if (arg0 == this) {
            return true;
        } else if (arg0 instanceof YPK) {
            return date.equals(((YPK) arg0).date)
                && x.equals(((YPK) arg0).x);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return date.hashCode() ^ x.hashCode();
    }
}

@Entity
@Access(AccessType.FIELD)
@Table(name = "Y")
@IdClass(YPK.class)
public class Y implements YY {

    @Id
    @Temporal(TemporalType.TIMESTAMP)
    Date date;


    @Id
    @ManyToOne(cascade = CascadeType.ALL)
    private X x;

    public Y(X x) {
        this.x = x;
        date = new DateTime().toDate();
    }

    protected Y() {
    }

    @Override
    public YPK id() {
        return new YPK(x,date);
    }

}

public class Test {

public static long orderId = 0;
public static long customerId = 0;

public static void main(String[] args) {
    Map<String,String> properties = new HashMap<String,String>(){
        {
        put("javax.persistence.jdbc.url","jdbc:derby://localhost:1527/myDB;create=false;");
        put("javax.persistence.jdbc.driver","org.apache.derby.jdbc.ClientDriver");
        put("javax.persistence.jdbc.user","myDbUser");
        put("javax.persistence.jdbc.password","passwd");
//        put(""eclipselink.ddl-generation","drop-and-create-tables");
        put(""eclipselink.ddl-generation","none");
        }
    };

    EntityManagerFactory emf =
        Persistence.createEntityManagerFactory("myPersistenceUnit",properties);
    final EntityManager em = emf.createEntityManager();

    X x =  new X();;
    saveItem(em,X.class,x);

    Y y =  new Y(x);;


    Y y2 =  new Y(x);;

    saveItems(em,Y.class,Arrays.asList(y,y2));
    saveItems(em,y2));

    Z z =  new Z(y2);;
    saveItems(em,Z.class,Arrays.asList(z));
}

private static <T extends YY> void saveItem(final EntityManager em,Class<T> clazz,T item) {
    synchronized(em) {
        EntityTransaction tx = em.getTransaction();
        saveItem(em,clazz,item,tx);
    }
}

private static <T extends YY> void saveItems(final EntityManager em,Collection<T> items) {
    synchronized (em) {
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            for (T item : items) {
                saveItem(em,tx);
            }
            tx.commit();
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
        }
    }
}

private static <T extends YY> void saveItem(final EntityManager em,T item,EntityTransaction tx) {
    Object id = item.id();
    T existing = em.find(clazz,id);

    if (existing != null) {
        em.merge(item);
    } else {
        em.persist(item);
    }
}

}

我运行程序一次,“drop-and-create-tables”取消注释,一切正常,因为数据库没有X条目.我注释掉drop-and-create-tables并再次运行它,但这次我得到以下错误.
谢谢

[EL Warning]: 2011-03-24 06:52:56.047--UnitOfWork(20391510)--Exception [EclipseLink-4002]
(Eclipse Persistence Services -
    2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException:
The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL110324065226450' defined on 'X'.
 Error Code: -1 Call:
 INSERT INTO X (ID) VALUES (?)  bind => [1 parameter bound]
 Query: InsertObjectQuery(com.test.X@1b6101e)
 Exception in thread "main" javax.persistence.RollbackException: Exception 
[EclipseLink-4002] (Eclipse Persistence Services -
    2.2.0.v20110202-r8913):
 org.eclipse.persistence.exceptions.DatabaseException
 Internal Exception: java.sql.SQLIntegrityConstraintViolationException:
 The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL110324065226450' defined on 'X'.
 Error Code: -1 Call: INSERT INTO X (ID) VALUES (?)     bind => [1 parameter bound]
 Query: InsertObjectQuery(com.test.X@1b6101e)   at
org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:102)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:63)
at com.test.Test.saveItems(Test.java:80)
at com.test.Test.main(Test.java:56)

日志在这里:
1st run successful
2nd run failure

解决方法

注意到你在打电话,

saveItems(em,y2));

两次?第一次通话或第二次通话时是否发生错误?

请包括您最好的登录.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读