Results 1 to 7 of 7

Thread: lazy initialization exception: no session bound to thread in equals method

  1. #1
    Join Date
    Feb 2007
    Posts
    291

    Default lazy initialization exception: no session bound to thread in equals method

    Hi i am using spring 3.1 with hibernate 4.3
    I have the following base class.
    Code:
    public abstract class Listing implements Serializable, ListingInterface {
    private static final long serialVersionUID = -3724317967386747246L;
    
    private Integer id;
    private String name;
    private String description;
    
    public Integer getId() {
        return this.id;
    }
    
    public String getName() {
        return this.name;
    }
    
    public String getDescription() {
        return this.description;
    }
    
    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(this.getName()).toHashCode();
    }
    
    @Override
    public boolean equals(final Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof Listing)) {
            return false;
        }
        final Listing other = Listing.class.cast(obj);
        return new EqualsBuilder().append(this.getName(), other.getName())
                .isEquals();
    }
    
    @Override
    public String toString() {
        return new ToStringBuilder(this).append("id", this.id)
                .append("name", this.name)
                .append("description", this.description).toString();
    }
    
    }
    a class that extends it.

    Code:
    public class Location extends Listing {
        // ... some other method. 
        @Override
    public boolean equals(final Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof Location)) {
            return false;
        }
        final Location other = Location.class.cast(obj);
        return new EqualsBuilder().append(this.getName(), other.getName())
                .isEquals();
    }
    }
    i have a junit test that extends abstractspringtransactionjunit4context

    Code:
    @Test
    public void testGetLocationGeographyByLocAndGeo() {
        final Location location = this.listingService.getLocationById(2);
        final Geography geography = this.geographyService
                .getGeographyById(LocationGeographyTestCase.TEST_LOAD_ID);
        final LocationGeography locationGeography = this.geographyService
                .getLocationGeographyByLocAndGeo(location, geography);
        Assert.assertEquals(location, locationGeography.getLocation());
        Assert.assertEquals(geography, locationGeography.getGeography());
    }
    here is the code where the error happens.
    Code:
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)     
    public LocationGeography getLocationGeographyByLocAndGeo(
    final Location location, final Geography geography) {                   
          return LocationGeography.class.cast(this.sessionFactory
                .getCurrentSession()
                .getNamedQuery("getLocationGeographyByLocAndGeo")
                .setEntity("location", location)
                .setEntity("geography", geography).uniqueResult()); 
    
    }
    part of hbm mapping.
    Code:
    	<class name="LocationGeography" mutable="false" table="LOCATION_GEOGRAPHY">
    		<cache usage="read-only" />
    		<composite-id access="field" mapped="false">
    			<key-many-to-one name="location" column="LOCATION_ID"
    				access="field" class="com.core.listing.domain.Location" />
    			<key-many-to-one name="geography" column="GEOGRAPHY_ID"
    				access="field" class="Geography" />
    		</composite-id>
    	</class>
    
    <query name="getLocationGeographyByLocAndGeo">
         <![CDATA[
            from LocationGeography locGeo
            WHERE locGeo.location = :location
            AND locGeo.geography = :geography
          ]]>
            <query-param name="location" type="com.core.listing.domain.Location" />
            <query-param name="geography" type="com.core.geography.domain.Geography" />
        </query>
    my error log.
    Code:
    Tests run: 5, Failures: 0, Errors: 1, Skipped: 1, Time elapsed: 0.543 sec <<< FAILURE!
    testGetLocationGeographyByLocAndGeo(com.core.test.LocationGeographyTestCase)  Time elapsed: 0.045 sec  <<< ERROR!
    org.springframework.orm.hibernate4.HibernateSystemException: could not initialize proxy - no Session; nested exception is org.hibernate.LazyInitializationException: could not initialize proxy - no Session
        at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:206)
        at org.springframework.orm.hibernate4.HibernateExceptionTranslator.convertHibernateAccessException(HibernateExceptionTranslator.java:56)
        at org.springframework.orm.hibernate4.HibernateExceptionTranslator.translateExceptionIfPossible(HibernateExceptionTranslator.java:43)
        at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
        at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
        at $Proxy24.getLocationGeographyByLocAndGeo(Unknown Source)
        at com.core.geography.service.impl.GeographyServiceImpl.getLocationGeographyByLocAndGeo(GeographyServiceImpl.java:100)
        at com.core.test.LocationGeographyTestCase.testGetLocationGeographyByLocAndGeo(LocationGeographyTestCase.java:59)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:601)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
        at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
        at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
        at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
        at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
        at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
        at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:119)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:101)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:601)
        at org.apache.maven.surefire.booter.ProviderFactory$ClassLoaderProxy.invoke(ProviderFactory.java:103)
        at $Proxy0.invoke(Unknown Source)
        at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:150)
        at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcess(SurefireStarter.java:91)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:69)
    Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
        at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:149)
        at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:195)
        at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
        at com.core.listing.domain.Location_$$_javassist_2.getName(Location_$$_javassist_2.java)
        at com.core.listing.domain.Location.equals(Location.java:129)
    None of my other test are having error except this one.

  2. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    Post your full test case, my guess is that it isn't transactional.

    Also your dao method has SUPPORTS as the propagation level which doesn't start a transaction it basically doesn't matter if there is or isn't a transaction. For Spring to interact with hibernate and make the getCurrentSession work there has to be an ongoing transaction.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  3. #3
    Join Date
    Feb 2007
    Posts
    291

    Default

    Quote Originally Posted by Marten Deinum View Post
    Post your full test case, my guess is that it isn't transactional.

    Also your dao method has SUPPORTS as the propagation level which doesn't start a transaction it basically doesn't matter if there is or isn't a transaction. For Spring to interact with hibernate and make the getCurrentSession work there has to be an ongoing transaction.
    Code:
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {
    		"classpath*:/applicationContext.xml"" })
    @TransactionConfiguration(transactionManager = "core.transactionManager")
    @ActiveProfiles("dev")
    public class LocGeoTestCase extends
    		AbstractTransactionalJUnit4SpringContextTests {
    	@Autowired
    	private ListingService listingService;
    
    	@Autowired
    	private GeographyService geographyService;
    
    	private final static int TEST_LOAD_ID = 1;
    
    @Test
    public void testGetLocationGeographyByLocAndGeo() {
        final Location location = this.listingService.getLocationById(2);
        final Geography geography = this.geographyService
                .getGeographyById(LocationGeographyTestCase.TEST_LOAD_ID);
        final LocationGeography locationGeography = this.geographyService
                .getLocationGeographyByLocAndGeo(location, geography);
        Assert.assertEquals(location, locationGeography.getLocation());
        Assert.assertEquals(geography, locationGeography.getGeography());
    }
    
    }

  4. #4
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    You are extending the correct class so your test should be transactional,however I nowhere in your stacktrace get the idea that it actually is transactional. Can you post your hibernate configuration.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  5. #5
    Join Date
    Feb 2007
    Posts
    291

    Default

    Quote Originally Posted by Marten Deinum View Post
    You are extending the correct class so your test should be transactional,however I nowhere in your stacktrace get the idea that it actually is transactional. Can you post your hibernate configuration.
    hibernate.cfg.xml
    Code:
    <!DOCTYPE hibernate-configuration SYSTEM
            "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    
    <hibernate-configuration>
        <session-factory>
            <property name="hibernate.query.substitutions">true 1, false 0</property>
            <mapping resource="Listing.hbm.xml"/>
            <mapping resource="Location.hbm.xml"/>
            <mapping resource="LocationGeography.hbm.xml"/>
            <mapping resource="Geography.hbm.xml"/>   
        </session-factory>
    </hibernate-configuration>
    applicationContext-test.xml

    Code:
     <bean id="sessionFactory"
    		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    		<property name="dataSource" ref="dataSource" />
    		<property name="configLocation" value="classpath:hibernate.cfg.xml" />
    		<property name="hibernateProperties" ref="hibernateProperties" />
    		<property name="packagesToScan" value="com.**.*.domain" />
    	</bean>
    	<util:properties id="hibernateProperties">
    		<prop key="hibernate.dialect">${hibernate.dialect}</prop>
    		<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
    		<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
    		<prop key="hibernate.use_outer_join">${hibernate.use_outer_join}</prop>
    		<prop key="hibernate.connection.pool_size">${hibernate.connection.pool_size}</prop>
    		<prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
    		<prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
    		<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
    		<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
    		<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
    	</util:properties>
        <!-- Transaction Manager for the tests -->
    	<bean id="core.transactionManager"
    		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    		<property name="sessionFactory" ref="sessionFactory" />
    	</bean>
    
    	<bean
    		class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
    		
    	<beans profile="dev">
    		<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    			destroy-method="close">
    			<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
    			<property name="url" value="${ds.url}" />
    			<property name="username" value="${ds.username}" />
    			<property name="password" value="${dspassword}" />
    			<property name="poolPreparedStatements" value="true" />
    			<property name="initialSize" value="0" />
    			<property name="maxActive" value="${ds.pool.maxActive}" />
    			<property name="maxIdle" value="${ds.pool.maxIdle}" />
    		</bean>
    	</beans>

    The problem is other test don't have this problem except this one.

  6. #6
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    In general you shouldn't be messing around with the hibernate.current_session_context_class as that breaks the spring integration for proper tx management. YOu should only change it if you use JTA.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  7. #7
    Join Date
    Feb 2007
    Posts
    291

    Default

    Quote Originally Posted by Marten Deinum View Post
    In general you shouldn't be messing around with the hibernate.current_session_context_class as that breaks the spring integration for proper tx management. YOu should only change it if you use JTA.

    Thanks. I have properties: hibernate.current_session_context_class=org.spring framework.orm.hibernate4.SpringSessionContext

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •