Announcement Announcement Module
Collapse
No announcement yet.
Failed to lazily initialize a collection - no session or ses Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Failed to lazily initialize a collection - no session or ses

    Hi friends :

    I want to load an Object,copy it's property and save it.But I get an Exception:
    Code:
    08:31:13,801 DEBUG BeanUtils:446 -         USING CONVERTER org.apache.commons.beanutils.converters.StringConverter@1ed5459
    08:31:13,842 ERROR LazyInitializationException:25 - Failed to lazily initialize a collection - no session or session was closed
    net.sf.hibernate.LazyInitializationException: Failed to lazily initialize a collection - no session or session was closed
    	at net.sf.hibernate.collection.PersistentCollection.initialize(PersistentCollection.java:209)
    	at net.sf.hibernate.collection.PersistentCollection.read(PersistentCollection.java:71)
    	at net.sf.hibernate.collection.Set.toString(Set.java:217)
    	at org.apache.commons.beanutils.BeanUtils.copyProperty(BeanUtils.java:331)
    	at org.apache.commons.beanutils.BeanUtils.copyProperties(BeanUtils.java:264)
    	at com.developcentry.building.service.UserDAOImpl.convertPToC(UserDAOImpl.java:185)
    	at com.developcentry.building.test.Test.main(Test.java:28)
    My code is simple:
    Code:
    public class UserDAOImpl extends HibernateDaoSupport implements UserDAO {
    public void  convertPtoC(String personID) throws DataAccessException {
         
                    C   c=new C();
            Person p=(Person )this.getHibernateTemplate().get(Person .class,personID);
            if(null!=p){
                          BeanUtils.copyProperties(c,p);
    
                   Object objid=this.getHibernateTemplate().save(sell);
            }else{
                throw new NoSuchPersonDataAccessException("No such Person!");
            }
    
        }
    Test code:
    Code:
     public static void main(String[] args) {
            String[] path={"file:/D:/eclipse/workspace/DeveloperCentry/src/spring-appContext.xml"};
            ApplicationContext xml=new FileSystemXmlApplicationContext(path);
     
            UserDAO udao=(UserDAO)xml.getBean("userDao");
            udao.convertPToC("1");
    
        }
    Why hibernate throws this Exception, What's wrong with my code? Thks[/code]

  • #2
    When trying to copy the object, BeanUtils is introspecting your object (reading it's properties). If your object is lazy-init and no session is open, resolving the properties will fail.
    Make sure the session of the object you try to copy is still open (by using an interceptor) or initialize completly your object before copying like this:

    Code:
    Hibernate.initialize(myObject);

    Comment


    • #3
      Strange!!!!

      Originally posted by costin
      When trying to copy the object, BeanUtils is introspecting your object (reading it's properties). If your object is lazy-init and no session is open, resolving the properties will fail.
      Make sure the session of the object you try to copy is still open (by using an interceptor) or initialize completly your object before copying like this:

      Code:
      Hibernate.initialize(myObject);
      It 's very very strange! I write a test code in my company today,all is well! No exception happen. The previouse code can work property!
      My code is:
      Code:
      public class SonDAOImp extends HibernateDaoSupport implements SonDAO {
      
          public void convertSToP(Class clazz, Serializable sid)
              throws DataAccessException {
              Object o = this.getHibernateTemplate().get(clazz, new Integer(3));
              Parent p = new Parent();
              try {
      			BeanUtils.copyProperties(p,o);
      		} catch (IllegalAccessException e) {
      			// TODO Auto-generated catch block
      			e.printStackTrace();
      		} catch (InvocationTargetException e) {
      			// TODO Auto-generated catch block
      			e.printStackTrace();
      		}
              this.getHibernateTemplate().save(p);
              this.getHibernateTemplate().delete(o);
          }
      }
      My Test code is:
      Code:
      public class Test {
          public static void main(String[] args) {
              ApplicationContext spring = new FileSystemXmlApplicationContext(
                      "D:\\jakarta-tomcat-5.0.16\\webapps\\spring\\WEB-INF\\springapp-servlet.xml");
      
              SonDAO sdao = (SonDAO) spring.getBean("sonDao");
              sdao.convertSToP(Son.class, "3");
          }
      }
      My config file:
      Code:
      <beans>
      
      
      <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName"><value>org.gjt.mm.mysql.Driver</value></property>
            <property name="url">
              <value>jdbc&#58;mysql&#58;//localhost&#58;3306/test2</value>
            </property>
            <property name="username"><value>root</value></property>
            <property name="password"><value></value></property>
          </bean>
        
      
      <bean id="MySessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
         <property name="mappingResources">
            <list>
              <value>lyo/test/Child.hbm.xml</value>
              <value>lyo/test/Parent.hbm.xml</value>
      		<value>lyo/test/Son.hbm.xml</value>
            </list>
         </property>
         <property name="hibernateProperties">
            <props>
              <prop key="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</prop>
              <prop key="hibernate.query.substitutions">true=1 false=0</prop>
              <prop key="hibernate.show_sql">true</prop>
              <prop key="hibernate.use_outer_join">false</prop>
            </props>
         </property>
         <property name="dataSource"><ref bean="dataSource"/></property>
      </bean> 
      <bean id="myTransactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
        <property name="sessionFactory">
          <ref bean="MySessionFactory"/>
        </property>
      </bean>
      
      
      <bean  id="sonDao" class="lyo.test.service.SonDAOImp">
      <property name="sessionFactory"> 
               <ref bean="MySessionFactory" /> 
            </property>
      </bean>
      </beans>
      xml config file:
      Code:
      	<class name="lyo.test.Son" table="Son">
      		<id name="id" type="integer" column="id">
      			<generator class="native"/>
      		</id>
      		<property name="sonname" column="sonname" type="string"/>
      		<property name="age" column="age" type="integer"/>
      	</class>
      Code:
      	<class name="Parent" table="parent">
      		<id
      			column="id"
      			name="parentId"
      			type="integer"
      		>
      			<generator class="native" />
      		</id>
      		<property
      			column="title"
      			length="20"
      			name="Title"
      			not-null="false"
      			type="string"
      		 />
      		<set
      			inverse="true"
      			&#91;code&#93;lazy="true"&#91;/code&#93;			name="ChildSet"
      			cascade="all"
      		>
      			<key column="father_id" />
      			<one-to-many class="Child" />
      		</set>
      	</class>
      The set is setting to lazy to "true" too. But why there is not exception when I copy properties?

      I mean that my later test is the same as previous, "lazy=true". But I can run without exception. It is strange. :?:

      Comment


      • #4
        You have to see the workflow inside your application.
        Remember that lazy exceptions will most probably appear when you have some relationship with another entity that hasn't been initialized.

        Comment


        • #5
          @PersistenceContext(unitName="bigbrother", type=PersistenceContextType.EXTENDED)
          public void setEntityManager(EntityManager entityManager) {
          this.entityManager = entityManager;
          }

          Comment

          Working...
          X