-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 8 posts ] 
Author Message
 Post subject: Spring + Hibernate = LazyLoadException
PostPosted: Fri Aug 19, 2005 2:34 pm 
Newbie

Joined: Fri Aug 19, 2005 2:03 pm
Posts: 3
Location: Toruń
Hi!

I've created my first very simple desktop application using Spring and Hibernate. I think that everything I've done well but this application throws a LazyLoadException :(



Hibernate version:
Hibernate 3.0.5

applicationContext.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName">
      <value>com.mysql.jdbc.Driver</value>
    </property>
    <property name="url">
      <value>jdbc:mysql://localhost/uk</value>
    </property>
    <property name="username">
      <value>root</value>
    </property>
    <property name="password">
      <value></value>
    </property>
  </bean>
  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
     <property name="mappingResources">
        <list>
           <value>/net/universekingdom/Ship.hbm.xml</value>
        </list>
     </property>
     <property name="hibernateProperties">
        <props>
           <prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
           <prop key="hibernate.hbm2ddl.auto">create</prop>
        </props>
     </property>
     <property name="dataSource">
      <ref local="dataSource"/>
     </property>
  </bean>
  <bean id="hibernateTxManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
     <property name="sessionFactory"><ref local="sessionFactory"></ref></property>
  </bean>
  <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    <property name="transactionManager"><ref local="hibernateTxManager"/></property>
  </bean>
  <bean id="shipDao" class="net.universekingdom.ShipDAOHibernate">
    <property name="sessionFactory">
      <ref local="sessionFactory"></ref>
    </property>
  </bean>
  <bean id="shipsListService" class="net.universekingdom.ShipsListServiceImpl">
    <constructor-arg type="net.universekingdom.ShipDAO">
      <ref local="shipDao" />
    </constructor-arg>
    <constructor-arg type="org.springframework.transaction.support.TransactionTemplate">
      <ref local="transactionTemplate" />
    </constructor-arg>
  </bean>
</beans>



Ship.hbm.xml

Code:
<hibernate-mapping
>
    <class
        name="net.universekingdom.Ship"
        table="SHIPS"
    >

        <id
            name="id"
            column="id"
            type="java.lang.Long"
        >
            <generator class="native">
            </generator>
        </id>

        <property
            name="name"
            type="java.lang.String"
            update="true"
            insert="true"
            column="name"
            length="64"
            not-null="true"
        />
    </class>

</hibernate-mapping>



Ship.java

Code:
package net.universekingdom;

/**
* @hibernate.class table = "SHIPS"
*
*/
public class Ship {
   public Ship() {
      name = "";
   }

   private String name;

   /**
    * @hibernate.property column = "name" length = "64" not-null = "true"
    * @return
    */
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   private Long id;

   /**
    * @hibernate.id column = "id" generator-class = "native"
    * @return
    */
   public Long getId() {
      return id;
   }

   public void setId(Long id) {
      this.id = id;
   }
}



ShipListServiceImpl.java

Code:
package net.universekingdom;

import java.util.List;
import java.util.Vector;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

public class ShipsListServiceImpl extends ShipsListService {

   private TransactionTemplate txTemplate;

   public ShipsListServiceImpl(ShipDAO shipDao, TransactionTemplate txTemplate) {
      super(shipDao);
      this.txTemplate = txTemplate;
   }

   public List getEnemyShips() {
      List l = (List) txTemplate.execute(new TransactionCallback() {

         public Object doInTransaction(TransactionStatus status) {
            Ship s = new Ship();
            s.setName("Jacek");
            shipDAO.insert(s);
            Ship ship = shipDAO.find("Jacek");
            List w = new Vector();
            w.add(ship);
            return w;
         }

      });
      return l;

   }
}


Code which is executed in main method
Code:
      InputStreamResource resource = new InputStreamResource(MyTest.class
            .getResourceAsStream("applicationContext.xml"));
      BeanFactory beanFactory = new XmlBeanFactory(resource);
      ShipsListService b = (ShipsListService) beanFactory
            .getBean("shipsListService");
      System.out.println(b.getEnemyShips().get(0));


When I run this code I get the following exception:

Full stack trace of any exception that occurs:
Code:
Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed
   at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:53)
   at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:80)
   at org.hibernate.proxy.CGLIBLazyInitializer.intercept(CGLIBLazyInitializer.java:133)
   at net.universekingdom.Ship$$EnhancerByCGLIB$$e195f361.toString(<generated>)
   at java.lang.String.valueOf(Unknown Source)
   at java.io.PrintStream.print(Unknown Source)
   at java.io.PrintStream.println(Unknown Source)
   at MyTest.main(MyTest.java:14)



What I'm doing wrong? What is incorrect?


Top
 Profile  
 
 Post subject:
PostPosted: Tue Aug 23, 2005 10:56 am 
Beginner
Beginner

Joined: Mon Apr 12, 2004 6:33 pm
Posts: 35
I ran into the same problem when migration from Hibernate 2 to 3.

If you use spring session are immediately closed. So all lazy stuff has to be initialized by then.

Hibernate 3 defaults to lazy loading of properties. Add the attribute layz="false" on the class tag in you hibernate mapping to change this behaviour.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Aug 23, 2005 11:00 am 
Senior
Senior

Joined: Tue Aug 03, 2004 2:11 pm
Posts: 142
Location: Somerset
kdekooter wrote:
I ran into the same problem when migration from Hibernate 2 to 3.

If you use spring session are immediately closed. So all lazy stuff has to be initialized by then.

Hibernate 3 defaults to lazy loading of properties. Add the attribute layz="false" on the class tag in you hibernate mapping to change this behaviour.



This from the migration guide

Association fetching strategies

Since it is best practice to map almost all classes and collections using lazy="true", that is now the default. Existing applications will need to explicitly specify lazy="false" on all non-lazy class and collection mappings.

The outer-join attribute is deprecated. Use fetch="join" and fetch="select" instead of outer-join="true" and outer-join="false". Existing applications may continue to use the outer-join attribute, or may use a text search/replace to migrate to use of the fetch attribute.

Beware, this means you have to put lazy="false" on all collection-mappings and classes which previously did not have a "lazy"-attribute.

A quick and dirty alternative for migration is also to put default-lazy="false" on all your hibernate-mapping elements.

_________________
On the information super B road


Top
 Profile  
 
 Post subject:
PostPosted: Tue Aug 23, 2005 5:02 pm 
Newbie

Joined: Fri Aug 19, 2005 2:03 pm
Posts: 3
Location: Toruń
I've changed the lazy attribute and now it's working! Big thanks for us for help me. Now, I can start to explore the possiblities of Hibernate and Spring. Thanks again for help me!


Top
 Profile  
 
 Post subject: May I ask an irrelevant question?
PostPosted: Tue Aug 23, 2005 5:39 pm 
Newbie

Joined: Tue Aug 16, 2005 2:20 am
Posts: 19
Location: California, USA
hi,

May I ask an irrelevant question? sorry can not help you since I am also new to hibernate.

I happened to use hibernate + spring as well.

My question is : are you using any tools to generate schema ?

Since my system is old, I already had all the table schema generated, so I care very little about schema generation tool; but I do care a lot about how to generate Java Object(POJO) given a table schema. Do you use any tool?

Many thanks and cheers.

xiuping


Top
 Profile  
 
 Post subject: Re: May I ask an irrelevant question?
PostPosted: Tue Aug 23, 2005 6:13 pm 
Newbie

Joined: Fri Aug 19, 2005 2:03 pm
Posts: 3
Location: Toruń
xyang wrote:

My question is : are you using any tools to generate schema ?

Since my system is old, I already had all the table schema generated, so I care very little about schema generation tool; but I do care a lot about how to generate Java Object(POJO) given a table schema. Do you use any tool?



Yes, I'm using SchemaExportTask to ANT (from Hibernate 3.0 library) to generate table schemas (from mapping [.hbm.xml] files). But I don't know how to generate Java Object from given table schema :(


Top
 Profile  
 
 Post subject: thanks.
PostPosted: Tue Aug 23, 2005 6:19 pm 
Newbie

Joined: Tue Aug 16, 2005 2:20 am
Posts: 19
Location: California, USA
hi jace,

thanks a lot.

So you wrote your Ship.java by hand. I did the same thing here and found very tedious, would like to try an automation tool.

I found this Hibernate Synchronizer, however, it generates a lot of other coede besides the POJOs such as initialization/session/transactions which Spring framework already took care of.

that is why I want to find out if there are other cleaner tools which focus on this.

thanks a lot for your kindly reply! If I ever find one good tool, I will let you know.

cheers,

xiuping


Top
 Profile  
 
 Post subject:
PostPosted: Tue Aug 23, 2005 7:09 pm 
Expert
Expert

Joined: Mon Feb 14, 2005 12:32 pm
Posts: 609
Location: Atlanta, GA - USA
kdekooter wrote:
I ran into the same problem when migration from Hibernate 2 to 3.

If you use spring session are immediately closed. So all lazy stuff has to be initialized by then.

Hibernate 3 defaults to lazy loading of properties. Add the attribute layz="false" on the class tag in you hibernate mapping to change this behaviour.


While I realize that setting lazy="false" on the class tag has you up and running, there is a real reason that lazy="true" is the default behavior.

In a large application, controlling the amount of data that is retrieved from the database can be critical to performance and you should only retrieve the data that is required for your specific task. A blanket set lazy='false' design strategy will cause you more problems in the long run. Read the documentation and learn how to control this process on a per-query basis.

_________________
Preston

Please don't forget to give credit if/when you get helpful information.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 8 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.