Search in sources :

Example 1 with PersistenceException

use of jakarta.persistence.PersistenceException in project spring-framework by spring-projects.

the class DefaultPersistenceUnitManager method scanPackage.

private void scanPackage(SpringPersistenceUnitInfo scannedUnit, String pkg) {
    if (this.componentsIndex != null) {
        Set<String> candidates = new HashSet<>();
        for (AnnotationTypeFilter filter : entityTypeFilters) {
            candidates.addAll(this.componentsIndex.getCandidateTypes(pkg, filter.getAnnotationType().getName()));
        }
        candidates.forEach(scannedUnit::addManagedClassName);
        Set<String> managedPackages = this.componentsIndex.getCandidateTypes(pkg, "package-info");
        managedPackages.forEach(scannedUnit::addManagedPackage);
        return;
    }
    try {
        String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(pkg) + CLASS_RESOURCE_PATTERN;
        Resource[] resources = this.resourcePatternResolver.getResources(pattern);
        MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
        for (Resource resource : resources) {
            try {
                MetadataReader reader = readerFactory.getMetadataReader(resource);
                String className = reader.getClassMetadata().getClassName();
                if (matchesFilter(reader, readerFactory)) {
                    scannedUnit.addManagedClassName(className);
                    if (scannedUnit.getPersistenceUnitRootUrl() == null) {
                        URL url = resource.getURL();
                        if (ResourceUtils.isJarURL(url)) {
                            scannedUnit.setPersistenceUnitRootUrl(ResourceUtils.extractJarFileURL(url));
                        }
                    }
                } else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
                    scannedUnit.addManagedPackage(className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
                }
            } catch (FileNotFoundException ex) {
            // Ignore non-readable resource
            }
        }
    } catch (IOException ex) {
        throw new PersistenceException("Failed to scan classpath for unlisted entity classes", ex);
    }
}
Also used : AnnotationTypeFilter(org.springframework.core.type.filter.AnnotationTypeFilter) CachingMetadataReaderFactory(org.springframework.core.type.classreading.CachingMetadataReaderFactory) MetadataReaderFactory(org.springframework.core.type.classreading.MetadataReaderFactory) Resource(org.springframework.core.io.Resource) FileNotFoundException(java.io.FileNotFoundException) MetadataReader(org.springframework.core.type.classreading.MetadataReader) CachingMetadataReaderFactory(org.springframework.core.type.classreading.CachingMetadataReaderFactory) IOException(java.io.IOException) URL(java.net.URL) PersistenceException(jakarta.persistence.PersistenceException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 2 with PersistenceException

use of jakarta.persistence.PersistenceException in project spring-framework by spring-projects.

the class OpenEntityManagerInViewInterceptor method preHandle.

@Override
public void preHandle(WebRequest request) throws DataAccessException {
    String key = getParticipateAttributeName();
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    if (asyncManager.hasConcurrentResult() && applyEntityManagerBindingInterceptor(asyncManager, key)) {
        return;
    }
    EntityManagerFactory emf = obtainEntityManagerFactory();
    if (TransactionSynchronizationManager.hasResource(emf)) {
        // Do not modify the EntityManager: just mark the request accordingly.
        Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST);
        int newCount = (count != null ? count + 1 : 1);
        request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
    } else {
        logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewInterceptor");
        try {
            EntityManager em = createEntityManager();
            EntityManagerHolder emHolder = new EntityManagerHolder(em);
            TransactionSynchronizationManager.bindResource(emf, emHolder);
            AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(emf, emHolder);
            asyncManager.registerCallableInterceptor(key, interceptor);
            asyncManager.registerDeferredResultInterceptor(key, interceptor);
        } catch (PersistenceException ex) {
            throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
        }
    }
}
Also used : WebAsyncManager(org.springframework.web.context.request.async.WebAsyncManager) EntityManager(jakarta.persistence.EntityManager) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) EntityManagerFactory(jakarta.persistence.EntityManagerFactory) PersistenceException(jakarta.persistence.PersistenceException) EntityManagerHolder(org.springframework.orm.jpa.EntityManagerHolder)

Example 3 with PersistenceException

use of jakarta.persistence.PersistenceException in project spring-framework by spring-projects.

the class HibernateTransactionManager method doCommit.

@Override
protected void doCommit(DefaultTransactionStatus status) {
    HibernateTransactionObject txObject = (HibernateTransactionObject) status.getTransaction();
    Transaction hibTx = txObject.getSessionHolder().getTransaction();
    Assert.state(hibTx != null, "No Hibernate transaction");
    if (status.isDebug()) {
        logger.debug("Committing Hibernate transaction on Session [" + txObject.getSessionHolder().getSession() + "]");
    }
    try {
        hibTx.commit();
    } catch (org.hibernate.TransactionException ex) {
        // assumably from commit call to the underlying JDBC connection
        throw new TransactionSystemException("Could not commit Hibernate transaction", ex);
    } catch (HibernateException ex) {
        // assumably failed to flush changes to database
        throw convertHibernateAccessException(ex);
    } catch (PersistenceException ex) {
        if (ex.getCause() instanceof HibernateException) {
            throw convertHibernateAccessException((HibernateException) ex.getCause());
        }
        throw ex;
    }
}
Also used : Transaction(org.hibernate.Transaction) HibernateException(org.hibernate.HibernateException) PersistenceException(jakarta.persistence.PersistenceException) TransactionSystemException(org.springframework.transaction.TransactionSystemException)

Example 4 with PersistenceException

use of jakarta.persistence.PersistenceException in project spring-framework by spring-projects.

the class HibernateTransactionManager method doRollback.

@Override
protected void doRollback(DefaultTransactionStatus status) {
    HibernateTransactionObject txObject = (HibernateTransactionObject) status.getTransaction();
    Transaction hibTx = txObject.getSessionHolder().getTransaction();
    Assert.state(hibTx != null, "No Hibernate transaction");
    if (status.isDebug()) {
        logger.debug("Rolling back Hibernate transaction on Session [" + txObject.getSessionHolder().getSession() + "]");
    }
    try {
        hibTx.rollback();
    } catch (org.hibernate.TransactionException ex) {
        throw new TransactionSystemException("Could not roll back Hibernate transaction", ex);
    } catch (HibernateException ex) {
        // Shouldn't really happen, as a rollback doesn't cause a flush.
        throw convertHibernateAccessException(ex);
    } catch (PersistenceException ex) {
        if (ex.getCause() instanceof HibernateException) {
            throw convertHibernateAccessException((HibernateException) ex.getCause());
        }
        throw ex;
    } finally {
        if (!txObject.isNewSession() && !this.hibernateManagedSession) {
            // Clear all pending inserts/updates/deletes in the Session.
            // Necessary for pre-bound Sessions, to avoid inconsistent state.
            txObject.getSessionHolder().getSession().clear();
        }
    }
}
Also used : Transaction(org.hibernate.Transaction) HibernateException(org.hibernate.HibernateException) PersistenceException(jakarta.persistence.PersistenceException) TransactionSystemException(org.springframework.transaction.TransactionSystemException)

Example 5 with PersistenceException

use of jakarta.persistence.PersistenceException in project spring-framework by spring-projects.

the class HibernateTemplate method doExecute.

/**
 * Execute the action specified by the given action object within a Session.
 * @param action callback object that specifies the Hibernate action
 * @param enforceNativeSession whether to enforce exposure of the native
 * Hibernate Session to callback code
 * @return a result object returned by the action, or {@code null}
 * @throws DataAccessException in case of Hibernate errors
 */
@Nullable
protected <T> T doExecute(HibernateCallback<T> action, boolean enforceNativeSession) throws DataAccessException {
    Assert.notNull(action, "Callback object must not be null");
    Session session = null;
    boolean isNew = false;
    try {
        session = obtainSessionFactory().getCurrentSession();
    } catch (HibernateException ex) {
        logger.debug("Could not retrieve pre-bound Hibernate session", ex);
    }
    if (session == null) {
        session = obtainSessionFactory().openSession();
        session.setHibernateFlushMode(FlushMode.MANUAL);
        isNew = true;
    }
    try {
        enableFilters(session);
        Session sessionToExpose = (enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session));
        return action.doInHibernate(sessionToExpose);
    } catch (HibernateException ex) {
        throw SessionFactoryUtils.convertHibernateAccessException(ex);
    } catch (PersistenceException ex) {
        if (ex.getCause() instanceof HibernateException) {
            throw SessionFactoryUtils.convertHibernateAccessException((HibernateException) ex.getCause());
        }
        throw ex;
    } catch (RuntimeException ex) {
        // Callback code threw application exception...
        throw ex;
    } finally {
        if (isNew) {
            SessionFactoryUtils.closeSession(session);
        } else {
            disableFilters(session);
        }
    }
}
Also used : HibernateException(org.hibernate.HibernateException) PersistenceException(jakarta.persistence.PersistenceException) Session(org.hibernate.Session) Nullable(org.springframework.lang.Nullable)

Aggregations

PersistenceException (jakarta.persistence.PersistenceException)9 HibernateException (org.hibernate.HibernateException)3 EntityManager (jakarta.persistence.EntityManager)2 EntityManagerFactory (jakarta.persistence.EntityManagerFactory)2 Transaction (org.hibernate.Transaction)2 Test (org.junit.jupiter.api.Test)2 DataAccessException (org.springframework.dao.DataAccessException)2 DataAccessResourceFailureException (org.springframework.dao.DataAccessResourceFailureException)2 EntityManagerHolder (org.springframework.orm.jpa.EntityManagerHolder)2 TransactionSystemException (org.springframework.transaction.TransactionSystemException)2 WebAsyncManager (org.springframework.web.context.request.async.WebAsyncManager)2 EntityExistsException (jakarta.persistence.EntityExistsException)1 EntityNotFoundException (jakarta.persistence.EntityNotFoundException)1 NoResultException (jakarta.persistence.NoResultException)1 NonUniqueResultException (jakarta.persistence.NonUniqueResultException)1 OptimisticLockException (jakarta.persistence.OptimisticLockException)1 TransactionRequiredException (jakarta.persistence.TransactionRequiredException)1 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 URL (java.net.URL)1