Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.hibernate.LazyInitializationException: could not initialize proxy -no Session

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.

like image 453
user2508111 Avatar asked Aug 19 '13 12:08

user2508111


2 Answers

@Test
@Transactional
public void myTestMethod ()
{
       assertTrue("Response Validating",validate(baseEntity,perform()));
}
like image 144
Prabhakaran Ramaswamy Avatar answered Oct 03 '22 07:10

Prabhakaran Ramaswamy


Annotate myTestMethod with @Transactional (assuming you're using annotation-based configuration).

like image 24
chrylis -cautiouslyoptimistic- Avatar answered Oct 03 '22 07:10

chrylis -cautiouslyoptimistic-