Search in sources :

Example 26 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class HibernatePersistenceProvider method getEntityManagerFactoryBuilderOrNull.

private EntityManagerFactoryBuilder getEntityManagerFactoryBuilderOrNull(String persistenceUnitName, Map properties, ClassLoader providedClassLoader, ClassLoaderService providedClassLoaderService) {
    log.tracef("Attempting to obtain correct EntityManagerFactoryBuilder for persistenceUnitName : %s", persistenceUnitName);
    final Map integration = wrap(properties);
    final List<ParsedPersistenceXmlDescriptor> units;
    try {
        units = PersistenceXmlParser.locatePersistenceUnits(integration);
    } catch (Exception e) {
        log.debug("Unable to locate persistence units", e);
        throw new PersistenceException("Unable to locate persistence units", e);
    }
    log.debugf("Located and parsed %s persistence units; checking each", units.size());
    if (persistenceUnitName == null && units.size() > 1) {
        // no persistence-unit name to look for was given and we found multiple persistence-units
        throw new PersistenceException("No name provided and multiple persistence units found");
    }
    for (ParsedPersistenceXmlDescriptor persistenceUnit : units) {
        log.debugf("Checking persistence-unit [name=%s, explicit-provider=%s] against incoming persistence unit name [%s]", persistenceUnit.getName(), persistenceUnit.getProviderClassName(), persistenceUnitName);
        final boolean matches = persistenceUnitName == null || persistenceUnit.getName().equals(persistenceUnitName);
        if (!matches) {
            log.debug("Excluding from consideration due to name mis-match");
            continue;
        }
        // See if we (Hibernate) are the persistence provider
        if (!ProviderChecker.isProvider(persistenceUnit, properties)) {
            log.debug("Excluding from consideration due to provider mis-match");
            continue;
        }
        if (providedClassLoaderService != null) {
            return getEntityManagerFactoryBuilder(persistenceUnit, integration, providedClassLoaderService);
        } else {
            return getEntityManagerFactoryBuilder(persistenceUnit, integration, providedClassLoader);
        }
    }
    log.debug("Found no matching persistence units");
    return null;
}
Also used : ParsedPersistenceXmlDescriptor(org.hibernate.jpa.boot.internal.ParsedPersistenceXmlDescriptor) PersistenceException(javax.persistence.PersistenceException) Map(java.util.Map) PersistenceException(javax.persistence.PersistenceException)

Example 27 with PersistenceException

use of javax.persistence.PersistenceException in project hibernate-orm by hibernate.

the class EntityManagerFactoryBuilderImpl method build.

@SuppressWarnings("unchecked")
public EntityManagerFactory build() {
    SessionFactoryBuilder sfBuilder = metadata().getSessionFactoryBuilder();
    populate(sfBuilder, standardServiceRegistry);
    try {
        return sfBuilder.build();
    } catch (Exception e) {
        throw persistenceException("Unable to build Hibernate SessionFactory", e);
    }
}
Also used : SessionFactoryBuilder(org.hibernate.boot.SessionFactoryBuilder) PersistenceException(javax.persistence.PersistenceException) EntityNotFoundException(javax.persistence.EntityNotFoundException)

Example 28 with PersistenceException

use of javax.persistence.PersistenceException in project camel by apache.

the class JpaPollingConsumer method receive.

@Override
public Exchange receive() {
    // resolve the entity manager before evaluating the expression
    final EntityManager entityManager = getTargetEntityManager(null, entityManagerFactory, getEndpoint().isUsePassedInEntityManager(), getEndpoint().isSharedEntityManager(), true);
    Object out = transactionTemplate.execute(new TransactionCallback<Object>() {

        public Object doInTransaction(TransactionStatus status) {
            if (getEndpoint().isJoinTransaction()) {
                entityManager.joinTransaction();
            }
            Query query = getQueryFactory().createQuery(entityManager);
            configureParameters(query);
            if (getEndpoint().isConsumeLockEntity()) {
                query.setLockMode(getLockModeType());
            }
            LOG.trace("Created query {}", query);
            Object answer;
            try {
                List<?> results = query.getResultList();
                if (results != null && results.size() == 1) {
                    // we only have 1 entity so return that
                    answer = results.get(0);
                } else {
                    // we have more data so return a list
                    answer = results;
                }
                // commit
                LOG.debug("Flushing EntityManager");
                entityManager.flush();
                // must clear after flush
                entityManager.clear();
            } catch (PersistenceException e) {
                LOG.info("Disposing EntityManager {} on {} due to coming transaction rollback", entityManager, this);
                entityManager.close();
                throw e;
            }
            return answer;
        }
    });
    Exchange exchange = createExchange(out, entityManager);
    exchange.getIn().setBody(out);
    return exchange;
}
Also used : Exchange(org.apache.camel.Exchange) EntityManager(javax.persistence.EntityManager) JpaHelper.getTargetEntityManager(org.apache.camel.component.jpa.JpaHelper.getTargetEntityManager) Query(javax.persistence.Query) PersistenceException(javax.persistence.PersistenceException) TransactionStatus(org.springframework.transaction.TransactionStatus) List(java.util.List)

Example 29 with PersistenceException

use of javax.persistence.PersistenceException in project VaadinUtils by rlsutton1.

the class ViolationConstraintHandler method expandException.

/**
 * logs the initial error and calls the recusive version of it'self. always
 * throws a runtime exception
 *
 * @param e
 */
static void expandException(Throwable e) {
    if (e instanceof RuntimeException && e.getCause() instanceof Buffered.SourceException) {
        SourceException ex = (Buffered.SourceException) e.getCause();
        if (ex.getCause() instanceof PersistenceException) {
            handlePersistenceException(ex);
        }
    }
    logger.error(e, e);
    handleConstraintViolationException(e, 5);
    throw new RuntimeException(e);
}
Also used : PersistenceException(javax.persistence.PersistenceException) SourceException(com.vaadin.data.Buffered.SourceException) SourceException(com.vaadin.data.Buffered.SourceException) Buffered(com.vaadin.data.Buffered)

Example 30 with PersistenceException

use of javax.persistence.PersistenceException in project Payara by payara.

the class DefaultProviderVerification method check.

public Result check(Descriptor descriptor) {
    PersistenceUnitDescriptor pu = PersistenceUnitDescriptor.class.cast(descriptor);
    Result result = getInitializedResult();
    result.setStatus(Result.PASSED);
    PersistenceProvider provider;
    final String appLocation = getVerifierContext().getAbstractArchive().getURI().getPath();
    final InstrumentableClassLoader cl = InstrumentableClassLoader.class.cast(pu.getParent().getClassLoader());
    PersistenceUnitInfo pi = new AVKPersistenceUnitInfoImpl(pu, appLocation, cl);
    logger.fine("PersistenceInfo for PU is :\n" + pi);
    Properties props = new Properties();
    // This property is set to indicate that TopLink should only
    // validate the descriptors etc. and not try to login to database.
    props.put(PersistenceUnitProperties.VALIDATION_ONLY_PROPERTY, // NOI18N
    "TRUE");
    // This property is used so that TopLink throws validation exceptions
    // as opposed to printing CONFIG level messages to console.
    // e.g. if mapping file does not exist, we will get an exception.
    props.put(PersistenceUnitProperties.THROW_EXCEPTIONS, // NOI18N
    "TRUE");
    // the following property is needed as it initializes the logger in TL
    props.put(PersistenceUnitProperties.TARGET_SERVER, // NOI18N
    "SunAS9");
    // Turn off enhancement during verification. For details,
    // refer to http://glassfish.dev.java.net/issues/show_bug.cgi?id=3295
    props.put(PersistenceUnitProperties.WEAVING, "FALSE");
    provider = new org.eclipse.persistence.jpa.PersistenceProvider();
    EntityManagerFactory emf = null;
    try {
        emf = provider.createContainerEntityManagerFactory(pi, props);
        logger.logp(Level.FINE, "DefaultProviderVerification", "check", "emf = {0}", emf);
    } catch (IntegrityException ie) {
        result.setStatus(Result.FAILED);
        addErrorDetails(result, getVerifierContext().getComponentNameConstructor());
        for (Object o : ie.getIntegrityChecker().getCaughtExceptions()) {
            Exception e = Exception.class.cast(o);
            result.addErrorDetails(e.getMessage());
        }
    } catch (ValidationException ve) {
        addErrorDetails(result, getVerifierContext().getComponentNameConstructor());
        result.failed(ve.getMessage());
        logger.logp(Level.FINE, "DefaultProviderVerification", "check", "Following exception occurred", ve);
    } catch (DatabaseException de) {
        addErrorDetails(result, getVerifierContext().getComponentNameConstructor());
        result.failed(de.getMessage());
        logger.logp(Level.FINE, "DefaultProviderVerification", "check", "Following exception occurred", de);
    } catch (PersistenceException pe) {
        addErrorDetails(result, getVerifierContext().getComponentNameConstructor());
        result.failed(pe.getMessage());
        logger.logp(Level.FINE, "DefaultProviderVerification", "check", "Following exception occurred", pe);
    } finally {
        if (emf != null) {
            emf.close();
        }
    }
    return result;
}
Also used : ValidationException(org.eclipse.persistence.exceptions.ValidationException) InstrumentableClassLoader(org.glassfish.api.deployment.InstrumentableClassLoader) PersistenceProvider(javax.persistence.spi.PersistenceProvider) IntegrityException(org.eclipse.persistence.exceptions.IntegrityException) AVKPersistenceUnitInfoImpl(com.sun.enterprise.tools.verifier.persistence.AVKPersistenceUnitInfoImpl) Properties(java.util.Properties) PersistenceUnitProperties(org.eclipse.persistence.config.PersistenceUnitProperties) PersistenceUnitInfo(javax.persistence.spi.PersistenceUnitInfo) PersistenceException(javax.persistence.PersistenceException) DatabaseException(org.eclipse.persistence.exceptions.DatabaseException) IntegrityException(org.eclipse.persistence.exceptions.IntegrityException) ValidationException(org.eclipse.persistence.exceptions.ValidationException) Result(com.sun.enterprise.tools.verifier.Result) EntityManagerFactory(javax.persistence.EntityManagerFactory) PersistenceException(javax.persistence.PersistenceException) DatabaseException(org.eclipse.persistence.exceptions.DatabaseException) PersistenceUnitDescriptor(com.sun.enterprise.deployment.PersistenceUnitDescriptor)

Aggregations

PersistenceException (javax.persistence.PersistenceException)191 Test (org.junit.Test)73 Session (org.hibernate.Session)57 EntityManager (javax.persistence.EntityManager)39 Transaction (org.hibernate.Transaction)34 EntityTransaction (javax.persistence.EntityTransaction)21 IOException (java.io.IOException)18 Query (javax.persistence.Query)18 ConstraintViolationException (org.hibernate.exception.ConstraintViolationException)18 List (java.util.List)16 ArrayList (java.util.ArrayList)14 TypedQuery (javax.persistence.TypedQuery)11 JPAQuery (org.datanucleus.api.jpa.JPAQuery)10 StaleObjectStateException (org.hibernate.StaleObjectStateException)10 SQLGrammarException (org.hibernate.exception.SQLGrammarException)8 HashMap (java.util.HashMap)6 Iterator (java.util.Iterator)6 Person (org.datanucleus.samples.annotations.models.company.Person)6 MessagesEvent (com.openmeap.event.MessagesEvent)5 SQLException (java.sql.SQLException)5