Search in sources :

Example 1 with EntityManager

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

the class JpaHelper method getTargetEntityManager.

/**
     * Gets or creates an {@link javax.persistence.EntityManager} to use.
     *
     * @param exchange                 the current exchange, or <tt>null</tt> if no exchange
     * @param entityManagerFactory     the entity manager factory (mandatory)
     * @param usePassedInEntityManager whether to use an existing {@link javax.persistence.EntityManager} which has been stored
     *                                 on the exchange in the header with key {@link org.apache.camel.component.jpa.JpaConstants#ENTITY_MANAGER}
     * @param useSharedEntityManager   whether to use SharedEntityManagerCreator if not already passed in                             
     * @return the entity manager (is never null)
     */
public static EntityManager getTargetEntityManager(Exchange exchange, EntityManagerFactory entityManagerFactory, boolean usePassedInEntityManager, boolean useSharedEntityManager, boolean allowRecreate) {
    EntityManager em = null;
    // favor using entity manager provided as a header from the end user
    if (exchange != null && usePassedInEntityManager) {
        em = exchange.getIn().getHeader(JpaConstants.ENTITY_MANAGER, EntityManager.class);
    }
    // then try reuse any entity manager which has been previously created and stored on the exchange
    if (em == null && exchange != null) {
        em = exchange.getProperty(JpaConstants.ENTITY_MANAGER, EntityManager.class);
    }
    if (em == null && useSharedEntityManager) {
        em = SharedEntityManagerCreator.createSharedEntityManager(entityManagerFactory);
    }
    if (em == null) {
        // create a new entity manager
        em = entityManagerFactory.createEntityManager();
        if (exchange != null) {
            // we want to reuse the EM so store as property and make sure we close it when done with the exchange
            exchange.setProperty(JpaConstants.ENTITY_MANAGER, em);
            exchange.addOnCompletion(new JpaCloseEntityManagerOnCompletion(em));
        }
    }
    if (allowRecreate && em == null || !em.isOpen()) {
        // create a new entity manager
        em = entityManagerFactory.createEntityManager();
        if (exchange != null) {
            // we want to reuse the EM so store as property and make sure we close it when done with the exchange
            exchange.setProperty(JpaConstants.ENTITY_MANAGER, em);
            exchange.addOnCompletion(new JpaCloseEntityManagerOnCompletion(em));
        }
    }
    return em;
}
Also used : EntityManager(javax.persistence.EntityManager)

Example 2 with EntityManager

use of javax.persistence.EntityManager 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 3 with EntityManager

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

the class JpaConsumer method processBatch.

public int processBatch(Queue<Object> exchanges) throws Exception {
    int total = exchanges.size();
    // limit if needed
    if (maxMessagesPerPoll > 0 && total > maxMessagesPerPoll) {
        LOG.debug("Limiting to maximum messages to poll " + maxMessagesPerPoll + " as there were " + total + " messages in this poll.");
        total = maxMessagesPerPoll;
    }
    for (int index = 0; index < total && isBatchAllowed(); index++) {
        // only loop if we are started (allowed to run)
        DataHolder holder = ObjectHelper.cast(DataHolder.class, exchanges.poll());
        EntityManager entityManager = holder.manager;
        Exchange exchange = holder.exchange;
        Object result = holder.result;
        // add current index and total as properties
        exchange.setProperty(Exchange.BATCH_INDEX, index);
        exchange.setProperty(Exchange.BATCH_SIZE, total);
        exchange.setProperty(Exchange.BATCH_COMPLETE, index == total - 1);
        // update pending number of exchanges
        pendingExchanges = total - index - 1;
        if (lockEntity(result, entityManager)) {
            // Run the @PreConsumed callback
            createPreDeleteHandler().deleteObject(entityManager, result, exchange);
            // process the current exchange
            LOG.debug("Processing exchange: {}", exchange);
            getProcessor().process(exchange);
            if (exchange.getException() != null) {
                // if we failed then throw exception
                throw exchange.getException();
            }
            // Run the @Consumed callback
            getDeleteHandler().deleteObject(entityManager, result, exchange);
        }
    }
    return total;
}
Also used : Exchange(org.apache.camel.Exchange) EntityManager(javax.persistence.EntityManager)

Example 4 with EntityManager

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

the class JpaProducerPassingEntityManagerTest method testRouteJpa.

@Test
public void testRouteJpa() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    context.startRoute("foo");
    JpaEndpoint jpa = context.getEndpoint("jpa://" + SendEmail.class.getName(), JpaEndpoint.class);
    EntityManagerFactory emf = jpa.getEntityManagerFactory();
    // The entity instance is different if it is retrieved from different EntityManager instance
    EntityManager entityManager = emf.createEntityManager();
    template.sendBody("direct:start", new SendEmail("foo@beer.org"));
    Exchange exchange = mock.getReceivedExchanges().get(0);
    SendEmail persistedEntity = exchange.getIn().getBody(SendEmail.class);
    SendEmail emfindEntity = entityManager.find(SendEmail.class, persistedEntity.getId());
    assertNotSame(emfindEntity, persistedEntity);
    entityManager.close();
    mock.reset();
    // The same EntityManager returns same entity instance from its 1st level cache
    entityManager = emf.createEntityManager();
    template.sendBodyAndHeader("direct:start", new SendEmail("bar@beer.org"), JpaConstants.ENTITYMANAGER, entityManager);
    exchange = mock.getReceivedExchanges().get(0);
    persistedEntity = exchange.getIn().getBody(SendEmail.class);
    emfindEntity = entityManager.find(SendEmail.class, persistedEntity.getId());
    assertSame(emfindEntity, persistedEntity);
    entityManager.close();
}
Also used : Exchange(org.apache.camel.Exchange) EntityManager(javax.persistence.EntityManager) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) EntityManagerFactory(javax.persistence.EntityManagerFactory) JpaEndpoint(org.apache.camel.component.jpa.JpaEndpoint) SendEmail(org.apache.camel.examples.SendEmail) Test(org.junit.Test)

Example 5 with EntityManager

use of javax.persistence.EntityManager in project che by eclipse.

the class JpaTckRepository method removeAll.

@Override
public void removeAll() throws TckRepositoryException {
    uow.begin();
    final EntityManager manager = managerProvider.get();
    try {
        manager.getTransaction().begin();
        // The query 'DELETE FROM Entity' won't be correct as it will ignore orphanRemoval
        // and may also ignore some configuration options, while EntityManager#remove won't
        manager.createQuery(format("SELECT e FROM %s e", getEntityName(entityClass)), entityClass).getResultList().forEach(manager::remove);
        manager.getTransaction().commit();
    } catch (RuntimeException x) {
        if (manager.getTransaction().isActive()) {
            manager.getTransaction().rollback();
        }
        throw new TckRepositoryException(x.getLocalizedMessage(), x);
    } finally {
        uow.end();
    }
}
Also used : EntityManager(javax.persistence.EntityManager)

Aggregations

EntityManager (javax.persistence.EntityManager)1395 Test (org.junit.Test)876 Priority (org.hibernate.envers.test.Priority)249 Query (javax.persistence.Query)200 TestForIssue (org.hibernate.testing.TestForIssue)97 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)87 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)79 List (java.util.List)69 NoResultException (javax.persistence.NoResultException)65 AbstractMetamodelSpecificTest (org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest)63 EntityManagerFactory (javax.persistence.EntityManagerFactory)56 HashMap (java.util.HashMap)50 StrTestEntity (org.hibernate.envers.test.entities.StrTestEntity)50 ArrayList (java.util.ArrayList)41 PersistenceException (javax.persistence.PersistenceException)40 EntityNotFoundException (javax.persistence.EntityNotFoundException)39 Transactional (com.google.inject.persist.Transactional)38 EntityTransaction (javax.persistence.EntityTransaction)36 Item (org.hibernate.jpa.test.Item)36 NonexistentEntityException (com.intel.mtwilson.as.controller.exceptions.NonexistentEntityException)34