Search in sources :

Example 1 with UnresolvableObjectException

use of org.hibernate.UnresolvableObjectException in project hibernate-orm by hibernate.

the class ReadOnlyProxyTest method testReadOnlyRefreshDeleted.

@Test
public void testReadOnlyRefreshDeleted() {
    Session s = openSession();
    s.setCacheMode(CacheMode.IGNORE);
    Transaction t = s.beginTransaction();
    DataPoint dp = new DataPoint();
    dp.setDescription("original");
    dp.setX(new BigDecimal(0.1d).setScale(19, BigDecimal.ROUND_DOWN));
    dp.setY(new BigDecimal(Math.cos(dp.getX().doubleValue())).setScale(19, BigDecimal.ROUND_DOWN));
    s.save(dp);
    t.commit();
    s.close();
    s = openSession();
    s.setCacheMode(CacheMode.IGNORE);
    t = s.beginTransaction();
    HibernateProxy dpProxy = (HibernateProxy) s.load(DataPoint.class, dp.getId());
    assertFalse(Hibernate.isInitialized(dpProxy));
    t.commit();
    s.close();
    s = openSession();
    s.setCacheMode(CacheMode.IGNORE);
    t = s.beginTransaction();
    dp = (DataPoint) s.get(DataPoint.class, dp.getId());
    s.delete(dp);
    s.flush();
    try {
        s.refresh(dp);
        fail("should have thrown UnresolvableObjectException");
    } catch (UnresolvableObjectException ex) {
    // expected
    } finally {
        t.rollback();
        s.close();
    }
    s = openSession();
    t = s.beginTransaction();
    s.setCacheMode(CacheMode.IGNORE);
    DataPoint dpProxyInit = (DataPoint) s.load(DataPoint.class, dp.getId());
    assertEquals("original", dp.getDescription());
    s.delete(dpProxyInit);
    t.commit();
    s.close();
    s = openSession();
    t = s.beginTransaction();
    assertTrue(dpProxyInit instanceof HibernateProxy);
    assertTrue(Hibernate.isInitialized(dpProxyInit));
    try {
        s.refresh(dpProxyInit);
        fail("should have thrown UnresolvableObjectException");
    } catch (UnresolvableObjectException ex) {
    // expected
    } finally {
        t.rollback();
        s.close();
    }
    s = openSession();
    t = s.beginTransaction();
    assertTrue(dpProxy instanceof HibernateProxy);
    try {
        s.refresh(dpProxy);
        assertFalse(Hibernate.isInitialized(dpProxy));
        Hibernate.initialize(dpProxy);
        fail("should have thrown UnresolvableObjectException");
    } catch (UnresolvableObjectException ex) {
    // expected
    } finally {
        t.rollback();
        s.close();
    }
}
Also used : Transaction(org.hibernate.Transaction) UnresolvableObjectException(org.hibernate.UnresolvableObjectException) HibernateProxy(org.hibernate.proxy.HibernateProxy) BigDecimal(java.math.BigDecimal) Session(org.hibernate.Session) Test(org.junit.Test)

Example 2 with UnresolvableObjectException

use of org.hibernate.UnresolvableObjectException in project hibernate-orm by hibernate.

the class DefaultRefreshEventListener method onRefresh.

/**
 * Handle the given refresh event.
 *
 * @param event The refresh event to be handled.
 */
public void onRefresh(RefreshEvent event, Map refreshedAlready) {
    final EventSource source = event.getSession();
    boolean isTransient;
    if (event.getEntityName() != null) {
        isTransient = !source.contains(event.getEntityName(), event.getObject());
    } else {
        isTransient = !source.contains(event.getObject());
    }
    if (source.getPersistenceContext().reassociateIfUninitializedProxy(event.getObject())) {
        if (isTransient) {
            source.setReadOnly(event.getObject(), source.isDefaultReadOnly());
        }
        return;
    }
    final Object object = source.getPersistenceContext().unproxyAndReassociate(event.getObject());
    if (refreshedAlready.containsKey(object)) {
        LOG.trace("Already refreshed");
        return;
    }
    final EntityEntry e = source.getPersistenceContext().getEntry(object);
    final EntityPersister persister;
    final Serializable id;
    if (e == null) {
        persister = source.getEntityPersister(event.getEntityName(), object);
        // refresh() does not pass an entityName
        id = persister.getIdentifier(object, event.getSession());
        if (LOG.isTraceEnabled()) {
            LOG.tracev("Refreshing transient {0}", MessageHelper.infoString(persister, id, source.getFactory()));
        }
        final EntityKey key = source.generateEntityKey(id, persister);
        if (source.getPersistenceContext().getEntry(key) != null) {
            throw new PersistentObjectException("attempted to refresh transient instance when persistent instance was already associated with the Session: " + MessageHelper.infoString(persister, id, source.getFactory()));
        }
    } else {
        if (LOG.isTraceEnabled()) {
            LOG.tracev("Refreshing ", MessageHelper.infoString(e.getPersister(), e.getId(), source.getFactory()));
        }
        if (!e.isExistsInDatabase()) {
            throw new UnresolvableObjectException(e.getId(), "this instance does not yet exist as a row in the database");
        }
        persister = e.getPersister();
        id = e.getId();
    }
    // cascade the refresh prior to refreshing this entity
    refreshedAlready.put(object, object);
    Cascade.cascade(CascadingActions.REFRESH, CascadePoint.BEFORE_REFRESH, source, persister, object, refreshedAlready);
    if (e != null) {
        final EntityKey key = source.generateEntityKey(id, persister);
        source.getPersistenceContext().removeEntity(key);
        if (persister.hasCollections()) {
            new EvictVisitor(source, object).process(object, persister);
        }
    }
    if (persister.canWriteToCache()) {
        Object previousVersion = null;
        if (persister.isVersionPropertyGenerated()) {
            // we need to grab the version value from the entity, otherwise
            // we have issues with generated-version entities that may have
            // multiple actions queued during the same flush
            previousVersion = persister.getVersion(object);
        }
        final EntityDataAccess cache = persister.getCacheAccessStrategy();
        final Object ck = cache.generateCacheKey(id, persister, source.getFactory(), source.getTenantIdentifier());
        final SoftLock lock = cache.lockItem(source, ck, previousVersion);
        cache.remove(source, ck);
        source.getActionQueue().registerProcess((success, session) -> cache.unlockItem(session, ck, lock));
    }
    evictCachedCollections(persister, id, source);
    String previousFetchProfile = source.getLoadQueryInfluencers().getInternalFetchProfile();
    source.getLoadQueryInfluencers().setInternalFetchProfile("refresh");
    Object result = persister.load(id, object, event.getLockOptions(), source);
    // If it was transient, then set it to the default for the source.
    if (result != null) {
        if (!persister.isMutable()) {
            // this is probably redundant; it should already be read-only
            source.setReadOnly(result, true);
        } else {
            source.setReadOnly(result, (e == null ? source.isDefaultReadOnly() : e.isReadOnly()));
        }
    }
    source.getLoadQueryInfluencers().setInternalFetchProfile(previousFetchProfile);
    UnresolvableObjectException.throwIfNull(result, id, persister.getEntityName());
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) Serializable(java.io.Serializable) PersistentObjectException(org.hibernate.PersistentObjectException) EntityKey(org.hibernate.engine.spi.EntityKey) EventSource(org.hibernate.event.spi.EventSource) EntityEntry(org.hibernate.engine.spi.EntityEntry) UnresolvableObjectException(org.hibernate.UnresolvableObjectException) EntityDataAccess(org.hibernate.cache.spi.access.EntityDataAccess) SoftLock(org.hibernate.cache.spi.access.SoftLock)

Example 3 with UnresolvableObjectException

use of org.hibernate.UnresolvableObjectException in project jo-client-platform by jo-source.

the class HibernateExceptionDecoratorImpl method decorate.

private Throwable decorate(final Throwable exception, final Throwable rootException) {
    if (exception instanceof ConstraintViolationException) {
        final ConstraintViolationException constViolationException = (ConstraintViolationException) exception;
        final String message = constViolationException.getMessage();
        final String constraintName = constViolationException.getConstraintName();
        final String userBaseMessage = Messages.getString("HibernateExceptionDecoratorImpl.database_constraint_violated");
        final String userMessage;
        if (!EmptyCheck.isEmpty(constraintName)) {
            userMessage = userBaseMessage.replace("%1", "'" + constraintName + "'");
        } else {
            final SQLException sqlException = constViolationException.getSQLException();
            if (sqlException != null) {
                if (!EmptyCheck.isEmpty(sqlException.getLocalizedMessage())) {
                    userMessage = sqlException.getLocalizedMessage();
                } else if (!EmptyCheck.isEmpty(sqlException.getMessage())) {
                    userMessage = sqlException.getMessage();
                } else {
                    userMessage = userBaseMessage.replace("%1", "");
                }
            } else {
                userMessage = userBaseMessage.replace("%1", "");
            }
        }
        return new ExecutableCheckException(null, message, userMessage);
    } else if (exception instanceof OptimisticLockException && exception.getCause() instanceof StaleObjectStateException) {
        return getStaleBeanException((StaleObjectStateException) exception);
    } else if (exception instanceof UnresolvableObjectException) {
        return getDeletedBeanException((UnresolvableObjectException) exception);
    } else if (exception instanceof JDBCException && !excludeJDBCExceptionDecoration((JDBCException) exception)) {
        return decorateJDBCException((JDBCException) exception);
    } else if (exception instanceof InvocationTargetException && ((InvocationTargetException) exception).getTargetException() != null) {
        return decorate(((InvocationTargetException) exception).getTargetException(), rootException);
    } else if (exception.getCause() != null) {
        return decorate(exception.getCause(), rootException);
    }
    return rootException;
}
Also used : JDBCException(org.hibernate.JDBCException) SQLException(java.sql.SQLException) UnresolvableObjectException(org.hibernate.UnresolvableObjectException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) OptimisticLockException(javax.persistence.OptimisticLockException) ExecutableCheckException(org.jowidgets.cap.common.api.exception.ExecutableCheckException) StaleObjectStateException(org.hibernate.StaleObjectStateException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 4 with UnresolvableObjectException

use of org.hibernate.UnresolvableObjectException in project hibernate-orm by hibernate.

the class ExceptionConverterImpl method convert.

@Override
public RuntimeException convert(HibernateException e, LockOptions lockOptions) {
    Throwable cause = e;
    if (cause instanceof StaleStateException) {
        final PersistenceException converted = wrapStaleStateException((StaleStateException) cause);
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof LockingStrategyException) {
        final PersistenceException converted = wrapLockException((HibernateException) cause, lockOptions);
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof org.hibernate.exception.LockTimeoutException) {
        final PersistenceException converted = wrapLockException((HibernateException) cause, lockOptions);
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof org.hibernate.PessimisticLockException) {
        final PersistenceException converted = wrapLockException((HibernateException) cause, lockOptions);
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof org.hibernate.QueryTimeoutException) {
        final QueryTimeoutException converted = new QueryTimeoutException(cause.getMessage(), cause);
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof ObjectNotFoundException) {
        final EntityNotFoundException converted = new EntityNotFoundException(cause.getMessage());
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof org.hibernate.NonUniqueObjectException) {
        final EntityExistsException converted = new EntityExistsException(cause.getMessage());
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof org.hibernate.NonUniqueResultException) {
        final NonUniqueResultException converted = new NonUniqueResultException(cause.getMessage());
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof UnresolvableObjectException) {
        final EntityNotFoundException converted = new EntityNotFoundException(cause.getMessage());
        handlePersistenceException(converted);
        return converted;
    } else if (cause instanceof QueryException) {
        return new IllegalArgumentException(cause);
    } else if (cause instanceof MultipleBagFetchException) {
        return new IllegalArgumentException(cause);
    } else if (cause instanceof TransientObjectException) {
        try {
            sharedSessionContract.markForRollbackOnly();
        } catch (Exception ne) {
            // we do not want the subsequent exception to swallow the original one
            log.unableToMarkForRollbackOnTransientObjectException(ne);
        }
        // Spec 3.2.3 Synchronization rules
        return new IllegalStateException(e);
    } else {
        final PersistenceException converted = new PersistenceException(cause);
        handlePersistenceException(converted);
        return converted;
    }
}
Also used : NonUniqueResultException(javax.persistence.NonUniqueResultException) TransientObjectException(org.hibernate.TransientObjectException) HibernateException(org.hibernate.HibernateException) LockingStrategyException(org.hibernate.dialect.lock.LockingStrategyException) EntityNotFoundException(javax.persistence.EntityNotFoundException) EntityExistsException(javax.persistence.EntityExistsException) LockTimeoutException(javax.persistence.LockTimeoutException) MultipleBagFetchException(org.hibernate.loader.MultipleBagFetchException) NoResultException(javax.persistence.NoResultException) UnresolvableObjectException(org.hibernate.UnresolvableObjectException) SQLException(java.sql.SQLException) NonUniqueResultException(javax.persistence.NonUniqueResultException) JDBCException(org.hibernate.JDBCException) EntityNotFoundException(javax.persistence.EntityNotFoundException) StaleStateException(org.hibernate.StaleStateException) OptimisticEntityLockException(org.hibernate.dialect.lock.OptimisticEntityLockException) LockingStrategyException(org.hibernate.dialect.lock.LockingStrategyException) EntityExistsException(javax.persistence.EntityExistsException) OptimisticLockException(javax.persistence.OptimisticLockException) StaleObjectStateException(org.hibernate.StaleObjectStateException) PessimisticLockException(javax.persistence.PessimisticLockException) PessimisticEntityLockException(org.hibernate.dialect.lock.PessimisticEntityLockException) TransientObjectException(org.hibernate.TransientObjectException) PersistenceException(javax.persistence.PersistenceException) RollbackException(javax.persistence.RollbackException) QueryTimeoutException(javax.persistence.QueryTimeoutException) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) HibernateException(org.hibernate.HibernateException) QueryException(org.hibernate.QueryException) QueryTimeoutException(javax.persistence.QueryTimeoutException) QueryException(org.hibernate.QueryException) StaleStateException(org.hibernate.StaleStateException) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) PersistenceException(javax.persistence.PersistenceException) UnresolvableObjectException(org.hibernate.UnresolvableObjectException) LockTimeoutException(javax.persistence.LockTimeoutException) MultipleBagFetchException(org.hibernate.loader.MultipleBagFetchException)

Aggregations

UnresolvableObjectException (org.hibernate.UnresolvableObjectException)4 SQLException (java.sql.SQLException)2 OptimisticLockException (javax.persistence.OptimisticLockException)2 JDBCException (org.hibernate.JDBCException)2 StaleObjectStateException (org.hibernate.StaleObjectStateException)2 Serializable (java.io.Serializable)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 BigDecimal (java.math.BigDecimal)1 EntityExistsException (javax.persistence.EntityExistsException)1 EntityNotFoundException (javax.persistence.EntityNotFoundException)1 LockTimeoutException (javax.persistence.LockTimeoutException)1 NoResultException (javax.persistence.NoResultException)1 NonUniqueResultException (javax.persistence.NonUniqueResultException)1 PersistenceException (javax.persistence.PersistenceException)1 PessimisticLockException (javax.persistence.PessimisticLockException)1 QueryTimeoutException (javax.persistence.QueryTimeoutException)1 RollbackException (javax.persistence.RollbackException)1 HibernateException (org.hibernate.HibernateException)1 ObjectNotFoundException (org.hibernate.ObjectNotFoundException)1 PersistentObjectException (org.hibernate.PersistentObjectException)1