在junit测试中运用openSessionInView

因为在spring提供的junit扩展中无法像web程序那样使用openSessionInView,

查了下官方信息,找到了如下解决方式

spring已经提供了针对此情况的应对方式,具体类为TransactionSynchronizationManager

使用此类可在事务中绑定一个hibernate的session对象,使之达到openSessionInView的效果.

具体列子:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class OpenSessionInViewTest extends AbstractTransactionalSpringContextTests {

        @Resource(name="hibernateSessionFactory")
	private SessionFactory sessionFactory;
       
        @Before
	public void init() {
		Session s = sessionFactory.openSession();
		TransactionSynchronizationManager.bindResource(sessionFactory,  
                new SessionHolder(s));  
	}

        @Test
	public void testQuery() {
		SessionHolder holder = (SessionHolder)TransactionSynchronizationManager.getResource(sessionFactory);
		Session session = holder.getSession();
		User user= (User)session.get(User.class, "abc0003");
		System.out.println(user.getId());
		Set<Book> books= user.getBooks();
		for (Book book: books) {
			System.out.println(book.getId());
		}
	}

        @After
	public void close() {
		SessionHolder holder = (SessionHolder)TransactionSynchronizationManager.getResource(sessionFactory);
		SessionFactoryUtils.closeSession(holder.getSession());
		TransactionSynchronizationManager.unbindResource(sessionFactory);  
	}
}

相关推荐