当前位置: 首页>>代码示例>>Java>>正文


Java EntityManagerHolder类代码示例

本文整理汇总了Java中org.springframework.orm.jpa.EntityManagerHolder的典型用法代码示例。如果您正苦于以下问题:Java EntityManagerHolder类的具体用法?Java EntityManagerHolder怎么用?Java EntityManagerHolder使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


EntityManagerHolder类属于org.springframework.orm.jpa包,在下文中一共展示了EntityManagerHolder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: doBegin

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
@Override
public void doBegin(Object transaction, final TransactionDefinition definition) {
    logger.info("MultiTenantJpaTransactionManager.doBegin()");
    super.doBegin(transaction, definition);
    EntityManagerHolder entityManagerHolder = (EntityManagerHolder) TransactionSynchronizationManager.getResource(getEntityManagerFactory());
    EntityManager entityManager = entityManagerHolder.getEntityManager();
    String currentTenant = tenantResolver.getCurrentTenant();
    logger.info("MultiTenantJpaTransactionManager.doBegin() - currentTenant: " + currentTenant);
    String currentTenantSet =  (String) entityManager.getProperties().get(MULTITENANT_PROPERTY_DEFAULT);
    logger.info("MultiTenantJpaTransactionManager.doBegin() - currentTenantSet: " + currentTenantSet);

    if(currentTenantSet != null && !currentTenantSet.equals(currentTenant)) {
        throw new IllegalStateException("Resource conflict - The EntityManager is already assigned to tenant : " + currentTenant);
    }
    entityManager.setProperty(MULTITENANT_PROPERTY_DEFAULT, currentTenant);
}
 
开发者ID:fdlessard,项目名称:SpringBootMagicEightBallProject,代码行数:17,代码来源:MultiTenantJpaTransactionManager.java

示例2: preHandle

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
@Override
public void preHandle(WebRequest request) throws DataAccessException {

	String participateAttributeName = getParticipateAttributeName();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult()) {
		if (applyCallableInterceptor(asyncManager, participateAttributeName)) {
			return;
		}
	}

	if (TransactionSynchronizationManager.hasResource(getEntityManagerFactory())) {
		// do not modify the EntityManager: just mark the request accordingly
		Integer count = (Integer) request.getAttribute(participateAttributeName, 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(getEntityManagerFactory(), emHolder);

			AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(getEntityManagerFactory(), emHolder);
			asyncManager.registerCallableInterceptor(participateAttributeName, interceptor);
			asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor);
		}
		catch (PersistenceException ex) {
			throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
		}
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:35,代码来源:OpenEntityManagerInViewInterceptor.java

示例3: afterCompletion

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
@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());
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:10,代码来源:OpenEntityManagerInViewInterceptor.java

示例4: closeEntityManager

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
/**
 * 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());
}
 
开发者ID:dewey-its,项目名称:apollo-custom,代码行数:15,代码来源:EntityManagerUtil.java

示例5: preHandle

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String participateAttributeName = getParticipateAttributeName();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult()) {
		if (applyCallableInterceptor(asyncManager, participateAttributeName)) {
			return;
		}
	}

	if (TransactionSynchronizationManager.hasResource(getEntityManagerFactory())) {
		// Do not modify the EntityManager: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(participateAttributeName, 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(getEntityManagerFactory(), emHolder);

			AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(getEntityManagerFactory(), emHolder);
			asyncManager.registerCallableInterceptor(participateAttributeName, interceptor);
			asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor);
		}
		catch (PersistenceException ex) {
			throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
		}
	}
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:34,代码来源:OpenEntityManagerInViewInterceptor.java

示例6: testPropertiesForSharedEntityManager1

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
/**
 * Binds an EMF to the thread and tests if EM with different properties
 * generate new EMs or not.
 */
@Test
public void testPropertiesForSharedEntityManager1() {
	Properties props = new Properties();
	props.put("foo", "bar");
	EntityManager em = mock(EntityManager.class);
	// only one call made  - the first EM definition wins (in this case the one w/ the properties)
	given(mockEmf.createEntityManager(props)).willReturn(em);
	given(em.getDelegate()).willReturn(new Object());
	given(em.isOpen()).willReturn(true);

	PersistenceAnnotationBeanPostProcessor pabpp = new MockPersistenceAnnotationBeanPostProcessor();
	DefaultPrivatePersistenceContextFieldWithProperties transactionalFieldWithProperties =
			new DefaultPrivatePersistenceContextFieldWithProperties();
	DefaultPrivatePersistenceContextField transactionalField = new DefaultPrivatePersistenceContextField();

	pabpp.postProcessPropertyValues(null, null, transactionalFieldWithProperties, "bean1");
	pabpp.postProcessPropertyValues(null, null, transactionalField, "bean2");

	assertNotNull(transactionalFieldWithProperties.em);
	assertNotNull(transactionalField.em);
	// the EM w/ properties will be created
	assertNotNull(transactionalFieldWithProperties.em.getDelegate());
	// bind em to the thread now since it's created
	try {
		TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(em));
		assertNotNull(transactionalField.em.getDelegate());
		verify(em).close();
	}
	finally {
		TransactionSynchronizationManager.unbindResource(mockEmf);
	}
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:37,代码来源:PersistenceInjectionTests.java

示例7: testPropertiesForSharedEntityManager2

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
@Test
public void testPropertiesForSharedEntityManager2() {
	Properties props = new Properties();
	props.put("foo", "bar");
	EntityManager em = mock(EntityManager.class);
	// only one call made  - the first EM definition wins (in this case the one w/o the properties)
	given(mockEmf.createEntityManager()).willReturn(em);
	given(em.getDelegate()).willReturn(new Object(), 2);
	given(em.isOpen()).willReturn(true);

	PersistenceAnnotationBeanPostProcessor pabpp = new MockPersistenceAnnotationBeanPostProcessor();
	DefaultPrivatePersistenceContextFieldWithProperties transactionalFieldWithProperties =
			new DefaultPrivatePersistenceContextFieldWithProperties();
	DefaultPrivatePersistenceContextField transactionalField = new DefaultPrivatePersistenceContextField();

	pabpp.postProcessPropertyValues(null, null, transactionalFieldWithProperties, "bean1");
	pabpp.postProcessPropertyValues(null, null, transactionalField, "bean2");

	assertNotNull(transactionalFieldWithProperties.em);
	assertNotNull(transactionalField.em);
	// the EM w/o properties will be created
	assertNotNull(transactionalField.em.getDelegate());
	// bind em to the thread now since it's created
	try {
		TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(em));
		assertNotNull(transactionalFieldWithProperties.em.getDelegate());
		verify(em).close();
	}
	finally {
		TransactionSynchronizationManager.unbindResource(mockEmf);
	}
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:33,代码来源:PersistenceInjectionTests.java

示例8: doGetActivePersistenceContext

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
protected EntityManager doGetActivePersistenceContext(Object testObject) {
	EntityManagerHolder entityManagerHolder = (EntityManagerHolder) TransactionSynchronizationManager.getResource(getPersistenceUnit(testObject));
   	if (entityManagerHolder != null && entityManagerHolder.getEntityManager() != null && entityManagerHolder.getEntityManager().isOpen()) {
   		return entityManagerHolder.getEntityManager();
   	}
   	return null;
}
 
开发者ID:linux-china,项目名称:unitils,代码行数:8,代码来源:JpaModule.java

示例9: doBefore

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
@Before
public void doBefore(){
	this.em = emf.createEntityManager();
	EntityManagerHolder emHolder = new EntityManagerHolder(em);
	TransactionSynchronizationManager.bindResource(emf,
			emHolder);
}
 
开发者ID:summerDp,项目名称:dpCms,代码行数:8,代码来源:JunitEntityManagerHolder.java

示例10: resolveEntityManager

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
/**
 * Fetches {@link javax.persistence.EntityManager} bound to the current Spring transaction or creates new manager.
 *
 * @param entityManagerFactory {@link javax.persistence.EntityManagerFactory} used either as a key for a Spring
 *                             transaction resource lookup or as a factory to create new
 *                             {@link javax.persistence.EntityManager}.
 * @return {@link javax.persistence.EntityManager} bound to the existing Spring transaction or new manager instance.
 */
public static EntityManager resolveEntityManager(EntityManagerFactory entityManagerFactory) {
    EntityManagerHolder entityManagerHolder =
            (EntityManagerHolder) TransactionSynchronizationManager.getResource(entityManagerFactory);
    if (entityManagerHolder != null) {
        return entityManagerHolder.getEntityManager();
    }
    return entityManagerFactory.createEntityManager();
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:17,代码来源:EntityManagers.java

示例11: cleanUpTransaction

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
private void cleanUpTransaction(final HttpServletRequest request) {
    if (noTransaction(request)) {
        return;
    }
    logDebug(request, "Cleaning up transaction");

    // Close any open iterators
    DataIteratorHelper.closeOpenIterators();

    // Close the session
    final EntityManagerHolder holder = getEntityManagerHolder();
    if (holder != null) {
        try {
            final EntityManager entityManager = holder.getEntityManager();
            if (entityManager.isOpen()) {
                entityManager.close();
            }
        } catch (final Exception e) {
            LOG.error("Error closing Hibernate session", e);
        }
        TransactionSynchronizationManager.unbindResourceIfPossible(entityManagerFactory);
    }

    // Cleanup the Spring transaction data
    TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
    TransactionSynchronizationManager.setActualTransactionActive(false);

    // Cleanup the current transaction data
    CurrentTransactionData.cleanup();

    request.removeAttribute(EXECUTION_RESULT_KEY);
}
 
开发者ID:mateli,项目名称:OpenCyclos,代码行数:33,代码来源:CyclosRequestProcessor.java

示例12: openReadOnlyConnection

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
private void openReadOnlyConnection(final HttpServletRequest request) {
    if (noTransaction(request)) {
        return;
    }
    logDebug(request, "Opening read-only transaction for include");

    final EntityManagerHolder holder = getEntityManagerHolder();
    holder.getEntityManager().setFlushMode(FlushModeType.COMMIT);
    if (holder.getEntityManager().getTransaction().isActive()) {
        holder.getEntityManager().getTransaction().setRollbackOnly();
    }
    TransactionSynchronizationManager.setCurrentTransactionReadOnly(true);
}
 
开发者ID:mateli,项目名称:OpenCyclos,代码行数:14,代码来源:CyclosRequestProcessor.java

示例13: rollbackReadOnlyConnection

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
private void rollbackReadOnlyConnection(final HttpServletRequest request) {
    if (noTransaction(request)) {
        return;
    }
    final EntityManagerHolder holder = getEntityManagerHolder();
    try {
        logDebug(request, "Rolling back read-only transaction");
        if (holder.getEntityManager().getTransaction().isActive()) {
            holder.getEntityManager().getTransaction().rollback();
        }
    } catch (final PersistenceException e) {
        throw new IllegalStateException(e);
    }
}
 
开发者ID:mateli,项目名称:OpenCyclos,代码行数:15,代码来源:CyclosRequestProcessor.java

示例14: retrieveBoundEntityManager

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
public static EntityManager retrieveBoundEntityManager() {
    Map<Object, Object> resources = TransactionSynchronizationManager.getResourceMap();
    for (Map.Entry<Object, Object> entry : resources.entrySet()) {
        if (entry.getKey() instanceof EntityManagerFactory) {
            EntityManagerFactory emf = (EntityManagerFactory) entry.getKey();
            //return the entityManager from the first found
            return  ((EntityManagerHolder) entry.getValue()).getEntityManager();
        }
    }
    throw new RuntimeException("Unable to restore skus from hydrated cache. Please make sure that the OpenEntityManagerInViewFilter is configured in web.xml for the blPU persistence unit.");
}
 
开发者ID:passion1014,项目名称:metaworks_framework,代码行数:12,代码来源:HydratedSetup.java

示例15: openEntityManager

import org.springframework.orm.jpa.EntityManagerHolder; //导入依赖的package包/类
/**
 * Mise en place du EntityManager
 */
public EntityManager openEntityManager() {
	if (TransactionSynchronizationManager.hasResource(entityManagerFactory)) {
		return ((EntityManagerHolder) TransactionSynchronizationManager.getResource(entityManagerFactory)).getEntityManager();
	} else {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		TransactionSynchronizationManager.bindResource(entityManagerFactory, new EntityManagerHolder(entityManager));
		return entityManager;
	}
}
 
开发者ID:openwide-java,项目名称:owsi-core-parent,代码行数:13,代码来源:EntityManagerUtils.java


注:本文中的org.springframework.orm.jpa.EntityManagerHolder类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。