问题
I am getting this bug when I run a test case(Junit) for spring application.
I searched for this problem and I got the information that whenever a lazy initialization occurs and my application tries to get second level data while session is closed(object become detached) then this error occurs, we can't make initialization as EAGER as its performance issue.
My testing class contains :
@RunWith(SpringJUnit4ClassRunner.class)
public class MyTestClass extends AbstractControllerTest {
@Rule
public TestName testMethodName = new TestName();
@Before
public void setUp() throws Exception
{
super.setUp();
}
@After
public void tearDown() throws Exception
{
super.tearDown();
}
@Test
public void myTestMethod ()
{
assertTrue("Response Validating",validate(baseEntity,perform()));
}
}
Is there a way that can I put method assertTrue("Response Validating",validate(baseEntity,perform())); in a transaction can bind with current session or with new session so that my detached object become persistent object and then My application can get second level data also. I searched for this problem and I found a solution on link : http://www.jroller.com/RickHigh/entry/hibernate_spring_simulating_an_opensessioninviewfilter but this link does not fulfil my requirement as it requires target object on which transaction is to be created.
回答1:
Annotate myTestMethod
with @Transactional
(assuming you're using annotation-based configuration).
回答2:
@Test
@Transactional
public void myTestMethod ()
{
assertTrue("Response Validating",validate(baseEntity,perform()));
}
回答3:
I got the solution for this problem. I was implementing OpenSessionInViewFilter in my testing code to overcome this problem but was doing silly mistake.
Please take a look on following code :
@Autowired
BeanFactory bf;
@Before
public void setUp() throws Exception
{
sessionFactory = (SessionFactory) bf.getBean("sessionFactory");
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
session.setFlushMode(FlushMode.NEVER);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}
@After
public void tearDown() throws Exception
{
super.tearDown();
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
Session session = sessionHolder.getSession();
SessionFactoryUtils.closeSession(session);
}
Earlier I was not using
session.setFlushMode(FlushMode.NEVER)
this was the mistake.
BTW thanks
来源:https://stackoverflow.com/questions/18314281/org-hibernate-lazyinitializationexception-could-not-initialize-proxy-no-sessio