Java Code Examples for org.springframework.transaction.support.TransactionSynchronizationManager#initSynchronization()

The following examples show how to use org.springframework.transaction.support.TransactionSynchronizationManager#initSynchronization() . 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: EntityManagerFactoryUtilsTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testDoGetEntityManagerWithTx() throws Exception {
	try {
		EntityManagerFactory factory = mock(EntityManagerFactory.class);
		EntityManager manager = mock(EntityManager.class);

		TransactionSynchronizationManager.initSynchronization();
		given(factory.createEntityManager()).willReturn(manager);

		// no tx active
		assertSame(manager, EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null));
		assertSame(manager, ((EntityManagerHolder)TransactionSynchronizationManager.unbindResource(factory)).getEntityManager());
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}

	assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
}
 
Example 2
Source File: EntityManagerFactoryUtilsTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoGetEntityManagerWithTx() throws Exception {
	try {
		EntityManagerFactory factory = mock(EntityManagerFactory.class);
		EntityManager manager = mock(EntityManager.class);

		TransactionSynchronizationManager.initSynchronization();
		given(factory.createEntityManager()).willReturn(manager);

		// no tx active
		assertSame(manager, EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null));
		assertSame(manager, ((EntityManagerHolder)TransactionSynchronizationManager.unbindResource(factory)).getEntityManager());
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}

	assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
}
 
Example 3
Source File: RoutingSynchronizationManager.java    From easyooo-framework with Apache License 2.0 6 votes vote down vote up
public static void initSynchronization(TransactionDefinition definition) throws IllegalStateException {
	if (isSynchronizationActive()) {
		throw new IllegalStateException("Cannot activate transaction synchronization - already active");
	}
	if(logger.isDebugEnabled()){
		logger.debug("Initializing transaction synchronization");
	}
	synchronizations.set(new LinkedHashMap<DataSource, ConnectionHolder>());
	definitions.set(definition);
	
	// 初始化Spring同步事务管理器,这使得Mybatis让Spring接管事务时,有一个判断标准,
	// 不会重复打开Session,也不会直接关闭Session
	// 具体请参看 org.mybatis.spring.SqlSessionUtils#getSqlSession
	// org.mybatis.spring.SqlSessionTemplate.SqlSessionInterceptor#invoke
	TransactionSynchronizationManager.initSynchronization();
}
 
Example 4
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testClobStringTypeWithFlushOnCommit() throws Exception {
	given(lobHandler.getClobAsString(rs, "column")).willReturn("content");

	ClobStringType type = new ClobStringType(lobHandler, null);
	assertEquals(1, type.sqlTypes().length);
	assertEquals(Types.CLOB, type.sqlTypes()[0]);
	assertEquals(String.class, type.returnedClass());
	assertTrue(type.equals("content", "content"));
	assertEquals("content", type.deepCopy("content"));
	assertFalse(type.isMutable());

	assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
	TransactionSynchronizationManager.initSynchronization();
	try {
		type.nullSafeSet(ps, "content", 1);
		List synchs = TransactionSynchronizationManager.getSynchronizations();
		assertEquals(1, synchs.size());
		((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}
	verify(lobCreator).setClobAsString(ps, 1, "content");
}
 
Example 5
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testBlobStringTypeWithNull() throws Exception {
	given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(null);

	BlobStringType type = new BlobStringType(lobHandler, null);
	assertEquals(null, type.nullSafeGet(rs, new String[] {"column"}, null));
	TransactionSynchronizationManager.initSynchronization();
	try {
		type.nullSafeSet(ps, null, 1);
		List synchs = TransactionSynchronizationManager.getSynchronizations();
		assertEquals(1, synchs.size());
		((TransactionSynchronization) synchs.get(0)).beforeCompletion();
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}

	verify(lobCreator).setBlobAsBytes(ps, 1, null);
}
 
Example 6
Source File: EntityManagerFactoryUtilsTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testDoGetEntityManagerWithTx() throws Exception {
	try {
		EntityManagerFactory factory = mock(EntityManagerFactory.class);
		EntityManager manager = mock(EntityManager.class);

		TransactionSynchronizationManager.initSynchronization();
		given(factory.createEntityManager()).willReturn(manager);

		// no tx active
		assertSame(manager, EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null));
		assertSame(manager, ((EntityManagerHolder)TransactionSynchronizationManager.unbindResource(factory)).getEntityManager());
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}

	assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
}
 
Example 7
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testBlobSerializableTypeWithNull() throws Exception {
	given(lobHandler.getBlobAsBinaryStream(rs, "column")).willReturn(null);

	BlobSerializableType type = new BlobSerializableType(lobHandler, null);
	assertEquals(null, type.nullSafeGet(rs, new String[] {"column"}, null));
	TransactionSynchronizationManager.initSynchronization();
	try {
		type.nullSafeSet(ps, null, 1);
		List synchs = TransactionSynchronizationManager.getSynchronizations();
		assertEquals(1, synchs.size());
		((TransactionSynchronization) synchs.get(0)).beforeCompletion();
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}
	verify(lobCreator).setBlobAsBytes(ps, 1, null);
}
 
Example 8
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testBlobByteArrayType() throws Exception {
	byte[] content = "content".getBytes();
	given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(content);

	BlobByteArrayType type = new BlobByteArrayType(lobHandler, null);
	assertEquals(1, type.sqlTypes().length);
	assertEquals(Types.BLOB, type.sqlTypes()[0]);
	assertEquals(byte[].class, type.returnedClass());
	assertTrue(type.equals(new byte[] {(byte) 255}, new byte[] {(byte) 255}));
	assertTrue(Arrays.equals(new byte[] {(byte) 255}, (byte[]) type.deepCopy(new byte[] {(byte) 255})));
	assertTrue(type.isMutable());

	assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null));
	TransactionSynchronizationManager.initSynchronization();
	try {
		type.nullSafeSet(ps, content, 1);
		List synchs = TransactionSynchronizationManager.getSynchronizations();
		assertEquals(1, synchs.size());
		((TransactionSynchronization) synchs.get(0)).beforeCompletion();
		((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}
	verify(lobCreator).setBlobAsBytes(ps, 1, content);
}
 
Example 9
Source File: BatchMetricsImplTest.java    From spring-boot-starter-batch-web with Apache License 2.0 5 votes vote down vote up
@Test
public void incrementBy1Transactional() throws Exception {
	// Given
	TransactionSynchronizationManager.initSynchronization();
	// When
	batchMetrics.increment("counter.test", 1L);
	TransactionSynchronizationUtils.triggerAfterCompletion(TransactionSynchronization.STATUS_COMMITTED);
	// Then
	TransactionSynchronizationManager.clearSynchronization();
}
 
Example 10
Source File: AbstractDatabasePopulatorTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
/**
 * See SPR-9457
 */
@Test
public void usesBoundConnectionIfAvailable() throws SQLException {
	TransactionSynchronizationManager.initSynchronization();
	Connection connection = DataSourceUtils.getConnection(db);
	DatabasePopulator populator = mock(DatabasePopulator.class);
	DatabasePopulatorUtils.execute(populator, db);
	verify(populator).populate(connection);
}
 
Example 11
Source File: ChainedTransactionManager.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Begin a transaction for all transaction managers {@inheritDoc}
 */
public TransactionStatus getTransaction( TransactionDefinition definition )
{
    if ( _transactionManagers.isEmpty( ) )
    {
        return null;
    }

    MultiTransactionStatus mts = new MultiTransactionStatus( _transactionManagers.get( 0 ) );

    if ( !TransactionSynchronizationManager.isSynchronizationActive( ) )
    {
        TransactionSynchronizationManager.initSynchronization( );
        mts.setNewSynchonization( );

        if ( _log.isDebugEnabled( ) )
        {
            _log.debug( "Begin transaction : " + mts.toString( ) );
        }
    }

    for ( PlatformTransactionManager transactionManager : _transactionManagers )
    {
        mts.getTransactionStatuses( ).put( transactionManager, transactionManager.getTransaction( definition ) );
    }

    return mts;
}
 
Example 12
Source File: TestInitializer.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    ApplicationContextProvider.setApplicationContext(ctx);
    ApplicationContextProvider.setBeanFactory((DefaultListableBeanFactory) ctx.getBeanFactory());

    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.initSynchronization();
    }

    domainLoader.load();

    contentLoader.load(
            SyncopeConstants.MASTER_DOMAIN,
            domainHolder.getDomains().get(SyncopeConstants.MASTER_DOMAIN));
}
 
Example 13
Source File: TestInitializer.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    ApplicationContextProvider.setApplicationContext(ctx);
    ApplicationContextProvider.setBeanFactory((DefaultListableBeanFactory) ctx.getBeanFactory());

    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
        TransactionSynchronizationManager.initSynchronization();
    }

    domainLoader.load();

    contentLoader.load(
            SyncopeConstants.MASTER_DOMAIN,
            domainHolder.getDomains().get(SyncopeConstants.MASTER_DOMAIN));
}
 
Example 14
Source File: AbstractDatabasePopulatorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * See SPR-9457
 */
@Test
public void usesBoundConnectionIfAvailable() throws SQLException {
	TransactionSynchronizationManager.initSynchronization();
	Connection connection = DataSourceUtils.getConnection(db);
	DatabasePopulator populator = mock(DatabasePopulator.class);
	DatabasePopulatorUtils.execute(populator, db);
	verify(populator).populate(connection);
}
 
Example 15
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testBlobSerializableType() throws Exception {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	ObjectOutputStream oos = new ObjectOutputStream(baos);
	oos.writeObject("content");
	oos.close();

	given(lobHandler.getBlobAsBinaryStream(rs, "column")).willReturn(new ByteArrayInputStream(baos.toByteArray()));

	BlobSerializableType type = new BlobSerializableType(lobHandler, null);
	assertEquals(1, type.sqlTypes().length);
	assertEquals(Types.BLOB, type.sqlTypes()[0]);
	assertEquals(Serializable.class, type.returnedClass());
	assertTrue(type.isMutable());

	assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
	TransactionSynchronizationManager.initSynchronization();
	try {
		type.nullSafeSet(ps, "content", 1);
		List synchs = TransactionSynchronizationManager.getSynchronizations();
		assertEquals(1, synchs.size());
		((TransactionSynchronization) synchs.get(0)).beforeCompletion();
		((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}
	verify(lobCreator).setBlobAsBytes(ps, 1, baos.toByteArray());
}
 
Example 16
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testBlobStringType() throws Exception {
	String content = "content";
	byte[] contentBytes = content.getBytes();
	given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(contentBytes);

	BlobStringType type = new BlobStringType(lobHandler, null);
	assertEquals(1, type.sqlTypes().length);
	assertEquals(Types.BLOB, type.sqlTypes()[0]);
	assertEquals(String.class, type.returnedClass());
	assertTrue(type.equals("content", "content"));
	assertEquals("content", type.deepCopy("content"));
	assertFalse(type.isMutable());

	assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null));
	TransactionSynchronizationManager.initSynchronization();
	try {
		type.nullSafeSet(ps, content, 1);
		List synchs = TransactionSynchronizationManager.getSynchronizations();
		assertEquals(1, synchs.size());
		((TransactionSynchronization) synchs.get(0)).beforeCompletion();
		((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}
	verify(lobCreator).setBlobAsBytes(ps, 1, contentBytes);
}
 
Example 17
Source File: LobTypeTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testClobStringTypeWithSynchronizedSession() throws Exception {
	SessionFactory sf = mock(SessionFactory.class);
	Session session = mock(Session.class);
	given(sf.openSession()).willReturn(session);
	given(session.getSessionFactory()).willReturn(sf);
	given(lobHandler.getClobAsString(rs, "column")).willReturn("content");

	ClobStringType type = new ClobStringType(lobHandler, null);
	assertEquals(1, type.sqlTypes().length);
	assertEquals(Types.CLOB, type.sqlTypes()[0]);
	assertEquals(String.class, type.returnedClass());
	assertTrue(type.equals("content", "content"));
	assertEquals("content", type.deepCopy("content"));
	assertFalse(type.isMutable());

	assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null));
	TransactionSynchronizationManager.initSynchronization();
	try {
		SessionFactoryUtils.getSession(sf, true);
		type.nullSafeSet(ps, "content", 1);
		List synchs = TransactionSynchronizationManager.getSynchronizations();
		assertEquals(2, synchs.size());
		assertTrue(synchs.get(0).getClass().getName().endsWith("SpringLobCreatorSynchronization"));
		((TransactionSynchronization) synchs.get(0)).beforeCompletion();
		((TransactionSynchronization) synchs.get(0)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
		((TransactionSynchronization) synchs.get(1)).beforeCompletion();
		((TransactionSynchronization) synchs.get(1)).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
	}
	finally {
		TransactionSynchronizationManager.clearSynchronization();
	}

	verify(session).close();
	verify(lobCreator).setClobAsString(ps, 1, "content");
}
 
Example 18
Source File: BatchMetricsImplTest.java    From spring-boot-starter-batch-web with Apache License 2.0 5 votes vote down vote up
@Test
public void submitTransactional() throws Exception {
	// Given
	TransactionSynchronizationManager.initSynchronization();
	// When
	batchMetrics.submit("counter.test", 1L);
	TransactionSynchronizationUtils.triggerAfterCompletion(TransactionSynchronization.STATUS_COMMITTED);
	// Then
	TransactionSynchronizationManager.clearSynchronization();
}
 
Example 19
Source File: AbstractDatabasePopulatorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * See SPR-9457
 */
@Test
public void usesBoundConnectionIfAvailable() throws SQLException {
	TransactionSynchronizationManager.initSynchronization();
	Connection connection = DataSourceUtils.getConnection(db);
	DatabasePopulator populator = mock(DatabasePopulator.class);
	DatabasePopulatorUtils.execute(populator, db);
	verify(populator).populate(connection);
}
 
Example 20
Source File: AbstractDatabasePopulatorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * See SPR-9457
 */
@Test
public void usesBoundConnectionIfAvailable() throws SQLException {
	TransactionSynchronizationManager.initSynchronization();
	Connection connection = DataSourceUtils.getConnection(db);
	DatabasePopulator populator = mock(DatabasePopulator.class);
	DatabasePopulatorUtils.execute(populator, db);
	verify(populator).populate(connection);
}