Search in sources :

Example 1 with EntityManagerProxy

use of org.springframework.orm.jpa.EntityManagerProxy in project spring-framework by spring-projects.

the class SharedEntityManagerFactoryTests method testValidUsage.

@Test
public void testValidUsage() {
    Object o = new Object();
    EntityManager mockEm = mock(EntityManager.class);
    given(mockEm.isOpen()).willReturn(true);
    EntityManagerFactory mockEmf = mock(EntityManagerFactory.class);
    given(mockEmf.createEntityManager()).willReturn(mockEm);
    SharedEntityManagerBean proxyFactoryBean = new SharedEntityManagerBean();
    proxyFactoryBean.setEntityManagerFactory(mockEmf);
    proxyFactoryBean.afterPropertiesSet();
    assertTrue(EntityManager.class.isAssignableFrom(proxyFactoryBean.getObjectType()));
    assertTrue(proxyFactoryBean.isSingleton());
    EntityManager proxy = proxyFactoryBean.getObject();
    assertSame(proxy, proxyFactoryBean.getObject());
    assertFalse(proxy.contains(o));
    assertTrue(proxy instanceof EntityManagerProxy);
    EntityManagerProxy emProxy = (EntityManagerProxy) proxy;
    try {
        emProxy.getTargetEntityManager();
        fail("Should have thrown IllegalStateException outside of transaction");
    } catch (IllegalStateException ex) {
    // expected
    }
    TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(mockEm));
    try {
        assertSame(mockEm, emProxy.getTargetEntityManager());
    } finally {
        TransactionSynchronizationManager.unbindResource(mockEmf);
    }
    assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
    verify(mockEm).contains(o);
    verify(mockEm).close();
}
Also used : EntityManager(javax.persistence.EntityManager) EntityManagerFactory(javax.persistence.EntityManagerFactory) EntityManagerHolder(org.springframework.orm.jpa.EntityManagerHolder) EntityManagerProxy(org.springframework.orm.jpa.EntityManagerProxy) Test(org.junit.Test)

Aggregations

EntityManager (javax.persistence.EntityManager)1 EntityManagerFactory (javax.persistence.EntityManagerFactory)1 Test (org.junit.Test)1 EntityManagerHolder (org.springframework.orm.jpa.EntityManagerHolder)1 EntityManagerProxy (org.springframework.orm.jpa.EntityManagerProxy)1