org.springframework.orm.jpa.EntityManagerFactoryUtils Java Examples

The following examples show how to use org.springframework.orm.jpa.EntityManagerFactoryUtils. 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
Source File: OpenEntityManagerInViewFilter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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
Source File: OpenEntityManagerInViewFilter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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
Source File: OpenEntityManagerInViewFilter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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
Source File: OpenEntityManagerInViewFilter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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
Source File: JPAGenericDAO.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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 #6
Source File: PersistenceImpl.java    From cuba with 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 #7
Source File: SpringEntityManagerSessionFactory.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@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 #8
Source File: SpringEntityManagerSessionFactory.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@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 #9
Source File: SimpleJpaQuery.java    From es with 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 #10
Source File: HibernateJpaDialect.java    From spring4-understanding with 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 #11
Source File: PersistenceAnnotationBeanPostProcessor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #12
Source File: OpenEntityManagerInViewInterceptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #13
Source File: OpenEntityManagerInViewInterceptor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #14
Source File: EntityManagerUtil.java    From apollo with 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 #15
Source File: DatabaseResourceReleaser.java    From multitenant with 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 #16
Source File: HibernateExceptionTranslator.java    From lams with 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) {
		if (ex.getCause() instanceof HibernateException) {
			return convertHibernateAccessException((HibernateException) ex.getCause());
		}
		return EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex);
	}
	return null;
}
 
Example #17
Source File: HibernateJpaDialect.java    From lams with 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
Source File: PersistenceAnnotationBeanPostProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #19
Source File: SpringEntityManagerSessionFactory.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
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 #20
Source File: OpenEntityManagerInViewInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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 #21
Source File: SpringEntityManagerSessionFactory.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
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 #22
Source File: SpringEntityManagerSessionFactory.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
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 #23
Source File: PersistenceAnnotationBeanPostProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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 #24
Source File: HibernateExceptionTranslator.java    From java-technology-stack with 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) {
		if (ex.getCause() instanceof HibernateException) {
			return convertHibernateAccessException((HibernateException) ex.getCause());
		}
		return EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex);
	}
	return null;
}
 
Example #25
Source File: HibernateJpaDialect.java    From java-technology-stack with 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 #26
Source File: HibernateJpaDialect.java    From spring-analysis-note with 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 #27
Source File: HibernateExceptionTranslator.java    From spring-analysis-note with 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) {
		if (ex.getCause() instanceof HibernateException) {
			return convertHibernateAccessException((HibernateException) ex.getCause());
		}
		return EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex);
	}
	return null;
}
 
Example #28
Source File: PersistenceAnnotationBeanPostProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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 #29
Source File: OpenEntityManagerInViewInterceptor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #30
Source File: PersistenceAnnotationBeanPostProcessor.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public void postProcessBeforeDestruction(Object bean, String beanName) {
	EntityManager emToClose = this.extendedEntityManagersToClose.remove(bean);
	EntityManagerFactoryUtils.closeEntityManager(emToClose);
}