PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

前端 未结 18 2622
醉酒成梦
醉酒成梦 2020-11-22 05:10

I have a JPA-persisted object model that contains a many-to-one relationship: an Account has many Transactions. A Transaction has one

18条回答
  •  迷失自我
    2020-11-22 05:31

    Maybe It is OpenJPA's bug, When rollback it reset the @Version field, but the pcVersionInit keep true. I have a AbstraceEntity which declared the @Version field. I can workaround it by reset the pcVersionInit field. But It is not a good idea. I think it not work when have cascade persist entity.

        private static Field PC_VERSION_INIT = null;
        static {
            try {
                PC_VERSION_INIT = AbstractEntity.class.getDeclaredField("pcVersionInit");
                PC_VERSION_INIT.setAccessible(true);
            } catch (NoSuchFieldException | SecurityException e) {
            }
        }
    
        public T call(final EntityManager em) {
                    if (PC_VERSION_INIT != null && isDetached(entity)) {
                        try {
                            PC_VERSION_INIT.set(entity, false);
                        } catch (IllegalArgumentException | IllegalAccessException e) {
                        }
                    }
                    em.persist(entity);
                    return entity;
                }
    
                /**
                 * @param entity
                 * @param detached
                 * @return
                 */
                private boolean isDetached(final Object entity) {
                    if (entity instanceof PersistenceCapable) {
                        PersistenceCapable pc = (PersistenceCapable) entity;
                        if (pc.pcIsDetached() == Boolean.TRUE) {
                            return true;
                        }
                    }
                    return false;
                }
    

提交回复
热议问题