在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); } }
相关推荐
shirleypaddy 2020-10-19
qingmumu 2020-10-19
lustdevil 2020-10-18
ganlulululu 2020-10-12
lustdevil 2020-08-03
lustdevil 2020-07-18
lustdevil 2020-06-25
lustdevil 2020-06-21
zhengzf0 2020-06-21
宿命java 2020-06-15
JackYin 2020-06-14
dongxurr 2020-06-07
snowphy 2020-06-06
zhengzf0 2020-05-28
81901836 2020-05-26
Julywhj 2020-05-26