Java Code Examples for org.springframework.orm.jpa.EntityManagerFactoryUtils

The following examples show how to use org.springframework.orm.jpa.EntityManagerFactoryUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Look up the EntityManagerFactory that this filter should use.
 * <p>The default implementation looks for a bean with the specified name
 * in Spring's root application context.
 * @return the EntityManagerFactory to use
 * @see #getEntityManagerFactoryBeanName
 */
protected EntityManagerFactory lookupEntityManagerFactory() {
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
	String emfBeanName = getEntityManagerFactoryBeanName();
	String puName = getPersistenceUnitName();
	if (StringUtils.hasLength(emfBeanName)) {
		return wac.getBean(emfBeanName, EntityManagerFactory.class);
	}
	else if (!StringUtils.hasLength(puName) && wac.containsBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME)) {
		return wac.getBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME, EntityManagerFactory.class);
	}
	else {
		// Includes fallback search for single EntityManagerFactory bean by type.
		return EntityManagerFactoryUtils.findEntityManagerFactory(wac, puName);
	}
}
 
Example 2
/**
 * Look up the EntityManagerFactory that this filter should use.
 * <p>The default implementation looks for a bean with the specified name
 * in Spring's root application context.
 * @return the EntityManagerFactory to use
 * @see #getEntityManagerFactoryBeanName
 */
protected EntityManagerFactory lookupEntityManagerFactory() {
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
	String emfBeanName = getEntityManagerFactoryBeanName();
	String puName = getPersistenceUnitName();
	if (StringUtils.hasLength(emfBeanName)) {
		return wac.getBean(emfBeanName, EntityManagerFactory.class);
	}
	else if (!StringUtils.hasLength(puName) && wac.containsBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME)) {
		return wac.getBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME, EntityManagerFactory.class);
	}
	else {
		// Includes fallback search for single EntityManagerFactory bean by type.
		return EntityManagerFactoryUtils.findEntityManagerFactory(wac, puName);
	}
}
 
Example 3
/**
 * Look up the EntityManagerFactory that this filter should use.
 * <p>The default implementation looks for a bean with the specified name
 * in Spring's root application context.
 * @return the EntityManagerFactory to use
 * @see #getEntityManagerFactoryBeanName
 */
protected EntityManagerFactory lookupEntityManagerFactory() {
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
	String emfBeanName = getEntityManagerFactoryBeanName();
	String puName = getPersistenceUnitName();
	if (StringUtils.hasLength(emfBeanName)) {
		return wac.getBean(emfBeanName, EntityManagerFactory.class);
	}
	else if (!StringUtils.hasLength(puName) && wac.containsBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME)) {
		return wac.getBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME, EntityManagerFactory.class);
	}
	else {
		// Includes fallback search for single EntityManagerFactory bean by type.
		return EntityManagerFactoryUtils.findEntityManagerFactory(wac, puName);
	}
}
 
Example 4
/**
 * Look up the EntityManagerFactory that this filter should use.
 * <p>The default implementation looks for a bean with the specified name
 * in Spring's root application context.
 * @return the EntityManagerFactory to use
 * @see #getEntityManagerFactoryBeanName
 */
protected EntityManagerFactory lookupEntityManagerFactory() {
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
	String emfBeanName = getEntityManagerFactoryBeanName();
	String puName = getPersistenceUnitName();
	if (StringUtils.hasLength(emfBeanName)) {
		return wac.getBean(emfBeanName, EntityManagerFactory.class);
	}
	else if (!StringUtils.hasLength(puName) && wac.containsBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME)) {
		return wac.getBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME, EntityManagerFactory.class);
	}
	else {
		// Includes fallback search for single EntityManagerFactory bean by type.
		return EntityManagerFactoryUtils.findEntityManagerFactory(wac, puName);
	}
}
 
Example 5
@Override
public void afterCompletion(WebRequest request, @Nullable Exception ex) throws DataAccessException {
	if (!decrementParticipateCount(request)) {
		EntityManagerHolder emHolder = (EntityManagerHolder)
				TransactionSynchronizationManager.unbindResource(obtainEntityManagerFactory());
		logger.debug("Closing JPA EntityManager in OpenEntityManagerInViewInterceptor");
		EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
	}
}
 
Example 6
/**
 * Find an EntityManagerFactory with the given name in the current
 * Spring application context.
 * @param unitName the name of the persistence unit (never empty)
 * @param requestingBeanName the name of the requesting bean
 * @return the EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
 */
protected EntityManagerFactory findNamedEntityManagerFactory(String unitName, @Nullable String requestingBeanName)
		throws NoSuchBeanDefinitionException {

	Assert.state(this.beanFactory != null, "ListableBeanFactory required for EntityManagerFactory bean lookup");

	EntityManagerFactory emf = EntityManagerFactoryUtils.findEntityManagerFactory(this.beanFactory, unitName);
	if (requestingBeanName != null && this.beanFactory instanceof ConfigurableBeanFactory) {
		((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(unitName, requestingBeanName);
	}
	return emf;
}
 
Example 7
Source Project: spring-analysis-note   Source File: HibernateJpaDialect.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
	if (ex instanceof HibernateException) {
		return convertHibernateAccessException((HibernateException) ex);
	}
	if (ex instanceof PersistenceException && ex.getCause() instanceof HibernateException) {
		return convertHibernateAccessException((HibernateException) ex.getCause());
	}
	return EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex);
}
 
Example 8
@Override
@Nullable
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
	if (ex instanceof HibernateException) {
		return convertHibernateAccessException((HibernateException) ex);
	}
	if (ex instanceof PersistenceException) {
		if (ex.getCause() instanceof HibernateException) {
			return convertHibernateAccessException((HibernateException) ex.getCause());
		}
		return EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex);
	}
	return null;
}
 
Example 9
@Override
public void afterCompletion(WebRequest request, @Nullable Exception ex) throws DataAccessException {
	if (!decrementParticipateCount(request)) {
		EntityManagerHolder emHolder = (EntityManagerHolder)
				TransactionSynchronizationManager.unbindResource(obtainEntityManagerFactory());
		logger.debug("Closing JPA EntityManager in OpenEntityManagerInViewInterceptor");
		EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
	}
}
 
Example 10
/**
 * Find an EntityManagerFactory with the given name in the current
 * Spring application context.
 * @param unitName the name of the persistence unit (never empty)
 * @param requestingBeanName the name of the requesting bean
 * @return the EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
 */
protected EntityManagerFactory findNamedEntityManagerFactory(String unitName, @Nullable String requestingBeanName)
		throws NoSuchBeanDefinitionException {

	Assert.state(this.beanFactory != null, "ListableBeanFactory required for EntityManagerFactory bean lookup");

	EntityManagerFactory emf = EntityManagerFactoryUtils.findEntityManagerFactory(this.beanFactory, unitName);
	if (requestingBeanName != null && this.beanFactory instanceof ConfigurableBeanFactory) {
		((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(unitName, requestingBeanName);
	}
	return emf;
}
 
Example 11
Source Project: java-technology-stack   Source File: HibernateJpaDialect.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
	if (ex instanceof HibernateException) {
		return convertHibernateAccessException((HibernateException) ex);
	}
	if (ex instanceof PersistenceException && ex.getCause() instanceof HibernateException) {
		return convertHibernateAccessException((HibernateException) ex.getCause());
	}
	return EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex);
}
 
Example 12
@Override
@Nullable
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
	if (ex instanceof HibernateException) {
		return convertHibernateAccessException((HibernateException) ex);
	}
	if (ex instanceof PersistenceException) {
		if (ex.getCause() instanceof HibernateException) {
			return convertHibernateAccessException((HibernateException) ex.getCause());
		}
		return EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex);
	}
	return null;
}
 
Example 13
public Session openSession(CommandContext commandContext) {
  EntityManager entityManager = EntityManagerFactoryUtils.getTransactionalEntityManager(entityManagerFactory);
  if (entityManager == null) {
    return new EntityManagerSessionImpl(entityManagerFactory, handleTransactions, closeEntityManager);
  }
  return new EntityManagerSessionImpl(entityManagerFactory, entityManager, false, false);
}
 
Example 14
public Session openSession() {
  EntityManager entityManager = EntityManagerFactoryUtils.getTransactionalEntityManager(entityManagerFactory);
  if (entityManager == null) {
    return new EntityManagerSessionImpl(entityManagerFactory, handleTransactions, closeEntityManager);
  }
  return new EntityManagerSessionImpl(entityManagerFactory, entityManager, false, false);
}
 
Example 15
@Override
public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
	if (!decrementParticipateCount(request)) {
		EntityManagerHolder emHolder = (EntityManagerHolder)
				TransactionSynchronizationManager.unbindResource(getEntityManagerFactory());
		logger.debug("Closing JPA EntityManager in OpenEntityManagerInViewInterceptor");
		EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
	}
}
 
Example 16
/**
 * Find an EntityManagerFactory with the given name in the current
 * Spring application context.
 * @param unitName the name of the persistence unit (never empty)
 * @param requestingBeanName the name of the requesting bean
 * @return the EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
 */
protected EntityManagerFactory findNamedEntityManagerFactory(String unitName, String requestingBeanName)
		throws NoSuchBeanDefinitionException {

	EntityManagerFactory emf = EntityManagerFactoryUtils.findEntityManagerFactory(this.beanFactory, unitName);
	if (this.beanFactory instanceof ConfigurableBeanFactory) {
		((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(unitName, requestingBeanName);
	}
	return emf;
}
 
Example 17
Source Project: lams   Source File: HibernateJpaDialect.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
	if (ex instanceof HibernateException) {
		return convertHibernateAccessException((HibernateException) ex);
	}
	if (ex instanceof PersistenceException && ex.getCause() instanceof HibernateException) {
		return convertHibernateAccessException((HibernateException) ex.getCause());
	}
	return EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex);
}
 
Example 18
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
	if (ex instanceof HibernateException) {
		return convertHibernateAccessException((HibernateException) ex);
	}
	if (ex instanceof PersistenceException) {
		if (ex.getCause() instanceof HibernateException) {
			return convertHibernateAccessException((HibernateException) ex.getCause());
		}
		return EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex);
	}
	return null;
}
 
Example 19
Source Project: multitenant   Source File: DatabaseResourceReleaser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void release(Organization organization) {
	entityManagerFactoryService.removeEntityManagerFactory(organization);
	EntityManager em = EntityManagerFactoryUtils.getTransactionalEntityManager(emf);
	if (!EmbeddedDatabaseConnection.isEmbedded(properties.determineDriverClassName())) {
		em.createNativeQuery("drop database " + organization.getId()).executeUpdate();
	}
	
}
 
Example 20
Source Project: apollo   Source File: EntityManagerUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * close the entity manager.
 * Use it with caution! This is only intended for use with async request, which Spring won't
 * close the entity manager until the async request is finished.
 */
public void closeEntityManager() {
  EntityManagerHolder emHolder = (EntityManagerHolder)
      TransactionSynchronizationManager.getResource(getEntityManagerFactory());
  if (emHolder == null) {
    return;
  }
  logger.debug("Closing JPA EntityManager in EntityManagerUtil");
  EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
}
 
Example 21
@Override
public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
	if (!decrementParticipateCount(request)) {
		EntityManagerHolder emHolder = (EntityManagerHolder)
				TransactionSynchronizationManager.unbindResource(getEntityManagerFactory());
		logger.debug("Closing JPA EntityManager in OpenEntityManagerInViewInterceptor");
		EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
	}
}
 
Example 22
/**
 * Find an EntityManagerFactory with the given name in the current
 * Spring application context.
 * @param unitName the name of the persistence unit (never empty)
 * @param requestingBeanName the name of the requesting bean
 * @return the EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
 */
protected EntityManagerFactory findNamedEntityManagerFactory(String unitName, String requestingBeanName)
		throws NoSuchBeanDefinitionException {

	EntityManagerFactory emf = EntityManagerFactoryUtils.findEntityManagerFactory(this.beanFactory, unitName);
	if (this.beanFactory instanceof ConfigurableBeanFactory) {
		((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(unitName, requestingBeanName);
	}
	return emf;
}
 
Example 23
Source Project: spring4-understanding   Source File: HibernateJpaDialect.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
	if (ex instanceof HibernateException) {
		return convertHibernateAccessException((HibernateException) ex);
	}
	if (ex instanceof PersistenceException && ex.getCause() instanceof HibernateException) {
		return convertHibernateAccessException((HibernateException) ex.getCause());
	}
	return EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex);
}
 
Example 24
@Override
public Session openSession() {
    EntityManager entityManager = EntityManagerFactoryUtils.getTransactionalEntityManager(entityManagerFactory);
    if (entityManager == null) {
        return new EntityManagerSessionImpl(entityManagerFactory, handleTransactions, closeEntityManager);
    }
    return new EntityManagerSessionImpl(entityManagerFactory, entityManager, false, false);
}
 
Example 25
@Override
public Session openSession(CommandContext commandContext) {
    EntityManager entityManager = EntityManagerFactoryUtils.getTransactionalEntityManager(entityManagerFactory);
    if (entityManager == null) {
        return new EntityManagerSessionImpl(entityManagerFactory, handleTransactions, closeEntityManager);
    }
    return new EntityManagerSessionImpl(entityManagerFactory, entityManager, false, false);
}
 
Example 26
Source Project: cuba   Source File: PersistenceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public EntityManager getEntityManager(String store) {
    if (!TransactionSynchronizationManager.isActualTransactionActive())
        throw new IllegalStateException("No active transaction");

    EntityManagerFactory emf;
    if (Stores.isMain(store))
        emf = this.jpaEmf;
    else
        emf = beanLocator.get("entityManagerFactory_" + store);

    javax.persistence.EntityManager jpaEm = EntityManagerFactoryUtils.doGetTransactionalEntityManager(emf, null, true);
    if (jpaEm == null) {
        throw new RuntimeException("Unable to get JPA EntityManager from EntityManagerFactoryUtils");
    }

    if (!jpaEm.isJoinedToTransaction()) {
        throw new IllegalStateException(String.format("No active transaction for %s database", store));
    }

    EntityManager entityManager = createEntityManager(jpaEm);

    EntityManagerContext ctx = contextHolder.get(store);
    if (ctx != null) {
        entityManager.setSoftDeletion(ctx.isSoftDeletion());
    } else {
        ctx = new EntityManagerContext();
        ctx.setSoftDeletion(isSoftDeletion());
        contextHolder.set(ctx, store);
        entityManager.setSoftDeletion(isSoftDeletion());
    }

    EntityManager emProxy = (EntityManager) Proxy.newProxyInstance(
            getClass().getClassLoader(),
            new Class[]{EntityManager.class},
            new EntityManagerInvocationHandler(entityManager, store)
    );
    return emProxy;
}
 
Example 27
/**
 * Return the Entity Manager
 * 
 * @return The Entity Manager
 */
public EntityManager getEM( )
{
    EntityManagerFactory emf = getEntityManagerFactory( );

    if ( TransactionSynchronizationManager.isSynchronizationActive( ) )
    {
        // first, get Spring entitymanager (if available)
        try
        {
            EntityManager em = EntityManagerFactoryUtils.getTransactionalEntityManager( emf );

            if ( em == null )
            {
                LOG.error( "getEM(  ) : no EntityManager found. Will use native entity manager factory [Transaction will not be supported]" );
            }
            else
            {
                LOG.debug( "EntityManager found for the current transaction : " + em.toString( ) + " - using Factory : " + emf.toString( ) );

                return em;
            }
        }
        catch( DataAccessResourceFailureException ex )
        {
            LOG.error( ex );
        }
    }

    LOG.error( "getEM(  ) : no EntityManager found. Will use native entity manager factory [Transaction will not be supported]" );

    if ( _defaultEM == null )
    {
        _defaultEM = emf.createEntityManager( );
    }
    return _defaultEM;
}
 
Example 28
Source Project: es   Source File: SimpleJpaQuery.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link SimpleJpaQuery} that encapsulates a simple query string.
 */
SimpleJpaQuery(JpaQueryMethod method, EntityManager em, String queryString) {

    super(method, em);

    this.method = method;
    this.query = new StringQuery(queryString);
    this.countQuery = new StringQuery(method.getCountQuery() == null ? QueryUtils.createCountQueryFor(queryString)
            : method.getCountQuery());

    Parameters parameters = method.getParameters();
    boolean hasPagingOrSortingParameter = parameters.hasPageableParameter() || parameters.hasSortParameter();

    if (method.isNativeQuery() && hasPagingOrSortingParameter) {
        throw new IllegalStateException("Cannot use native queries with dynamic sorting and/or pagination!");
    }

    EntityManager target = null;
    // Try to create a Query object already to fail fast
    if (!method.isNativeQuery()) {
        try {
            target = em.getEntityManagerFactory().createEntityManager();
            target.createQuery(query.getQuery());
        } catch (RuntimeException e) {
            // Needed as there's ambiguities in how an invalid query string shall be expressed by the persistence provider
            // http://java.net/projects/jpa-spec/lists/jsr338-experts/archive/2012-07/message/17
            throw e instanceof IllegalArgumentException ? e : new IllegalArgumentException(e);
        } finally {
            EntityManagerFactoryUtils.closeEntityManager(target);
        }
    }
}
 
Example 29
public Session openSession() {
  EntityManager entityManager = EntityManagerFactoryUtils.getTransactionalEntityManager(entityManagerFactory);
  if (entityManager == null) {
    return new EntityManagerSessionImpl(entityManagerFactory, handleTransactions, closeEntityManager);
  }
  return new EntityManagerSessionImpl(entityManagerFactory, entityManager, false, false);
}
 
Example 30
@Override
public void postProcessBeforeDestruction(Object bean, String beanName) {
	EntityManager emToClose = this.extendedEntityManagersToClose.remove(bean);
	EntityManagerFactoryUtils.closeEntityManager(emToClose);
}