-->
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.  [ 4 posts ] 
Author Message
 Post subject: LazyInitializationException
PostPosted: Fri Feb 23, 2007 4:02 pm 
Newbie

Joined: Thu Jun 22, 2006 7:19 am
Posts: 14
Hi

I am workin on a web application, but when i try to get an object i get this error:

Code:
Hibernate: select category0_.id as id0_, category0_.name as name0_, category0_.description as descript3_0_, category0_.icon as icon0_, category0_.tags as tags0_, category0_.parent as parent0_ from Categories category0_ where category0_.parent is null
ERROR - failed to lazily initialize a collection of role: es.bytelecom.wicketiki.objects.Category.children, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: es.bytelecom.wicketiki.objects.Category.children, no session or session was closed
        at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
        at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
        at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:97)
        at org.hibernate.collection.PersistentBag.size(PersistentBag.java:225)
        at wicket.markup.html.list.ListView.getViewSize(ListView.java:220)
        at wicket.markup.html.list.ListView.internalOnAttach(ListView.java:536)
        at wicket.Component.internalAttach(Component.java:2572)
        at wicket.MarkupContainer.internalAttach(MarkupContainer.java:341)
        at wicket.MarkupContainer.internalAttach(MarkupContainer.java:354)
        at wicket.Page.renderPage(Page.java:383)
        at wicket.protocol.http.WebRequestCycle.redirectTo(WebRequestCycle.java:160)
        at wicket.request.target.component.PageRequestTarget.respond(PageRequestTarget.java:60)
        at wicket.request.compound.DefaultResponseStrategy.respond(DefaultResponseStrategy.java:49)
        at wicket.request.compound.AbstractCompoundRequestCycleProcessor.respond(AbstractCompoundRequestCycleProcessor.java:66)
        at wicket.RequestCycle.doProcessEventsAndRespond(RequestCycle.java:902)
        at wicket.RequestCycle.processEventsAndRespond(RequestCycle.java:929)
        at wicket.RequestCycle.step(RequestCycle.java:1010)
        at wicket.RequestCycle.steps(RequestCycle.java:1084)
        at wicket.RequestCycle.request(RequestCycle.java:454)
        at wicket.protocol.http.WicketServlet.doGet(WicketServlet.java:219)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
        at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
        at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
        at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
        at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
        at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)


This is mu hibernate.cfg.xml:

Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
   
    <session-factory>
       
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/wicketiki</property>
        <property name="connection.username">root</property>
        <property name="connection.password">******</property>
       
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
       
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
       
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
       
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
       
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
       
        <mapping class="es.bytelecom.wicketiki.objects.Category" />
        <mapping class="es.bytelecom.wicketiki.objects.User" />
        <mapping class="es.bytelecom.wicketiki.objects.Page" />
       
    </session-factory>
   
</hibernate-configuration>


The category class:

Code:

/**
* Entity class Category
*
* @author Juan
*/
@Entity()
@Table(name = "Categories")
@NamedQueries( {
    @NamedQuery(name = "Category.findById", query = "SELECT c FROM Category c WHERE c.id = :id"),
    @NamedQuery(name = "Category.findByName", query = "SELECT c FROM Category c WHERE c.name = :name"),
    @NamedQuery(name = "Category.findByDescription", query = "SELECT c FROM Category c WHERE c.description = :description"),
    @NamedQuery(name = "Category.findByIcon", query = "SELECT c FROM Category c WHERE c.icon = :icon"),
    @NamedQuery(name = "Category.findByTags", query = "SELECT c FROM Category c WHERE c.tags = :tags"),
    @NamedQuery(name = "Category.findByParent", query = "SELECT c FROM Category c WHERE c.parent = :parent")
})
public class Category implements Serializable {
   
   
    public static List<Category> getRootCategories() {
       
        List<Category> categories = new ArrayList<Category>();
       
        Session session = HibernateUtil.getCurrentSession();
        session.beginTransaction();
        categories = (List<Category>) session.createQuery("from Category c where c.parent is null").list();
        session.getTransaction().commit();
        return categories;
       
    }
   
   
   
   
    @ManyToMany(
    cascade={CascadeType.PERSIST, CascadeType.MERGE},
            targetEntity=Page.class
            )
            @JoinTable(
    name="CategoriesPages",
            joinColumns={@JoinColumn(name="categoryid")},
            inverseJoinColumns={@JoinColumn(name="pageid")}
    )
    private List<Page> pages;
   
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
   
    @Column(name = "name")
    private String name;
   
    @Column(name = "description")
    private String description;
   
    @Column(name = "icon")
    private String icon;
   
    @Column(name = "tags")
    private String tags;
   
   
    @OneToMany(mappedBy="parent")
    private List<Category> children;
   
    @ManyToOne
    @JoinColumn(name="parent")
    @NotFound(action=NotFoundAction.IGNORE)
    private Category parent;
 
    // Contructors, getters and setter
 
}


The HibernaUtil class:
Code:
/*
* HibernateUtil.java
*
* Creado el 17 de febrero de 2007, 16:00
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

package es.bytelecom.wicketiki;

import es.bytelecom.wicketiki.objects.Category;
import java.io.File;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

/**
*
* @author Juan
*/
public class HibernateUtil {
   
    private static Logger log = LogManager.getLogger(HibernateUtil.class);
    private static SessionFactory sessionFactory;
   
    public static void configure(String hibernateXmlCfgFile) {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = new AnnotationConfiguration().configure(new File(hibernateXmlCfgFile)).buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            log.error("Initial SessionFactory creation failed.", ex);
            throw new ExceptionInInitializerError(ex);
        }
               
    }
   
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
   
   
    public static void saveOrUpdate(Object o) {
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        session.saveOrUpdate(o);
        session.getTransaction().commit();
    }
   
   
    public static void delete(Object o) {
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        session.delete(o);
        session.getTransaction().commit();
    }
   
    public static Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }
   
}


Thanks in advance.

Hibernate version: 3.2


Top
 Profile  
 
 Post subject:
PostPosted: Fri Feb 23, 2007 5:02 pm 
Regular
Regular

Joined: Sun Sep 17, 2006 2:48 am
Posts: 81
Location: California
One of your object has a list of children. They are lazily loaded. You are trying to access these children data after the session is closed.
Suggesstion : Either keep the session open till that time OR load these children eagerly


Top
 Profile  
 
 Post subject:
PostPosted: Fri Feb 23, 2007 5:11 pm 
Newbie

Joined: Thu Jun 22, 2006 7:19 am
Posts: 14
Well, exactly. I have changed the declaration of the children property and now i don't get the error:

Code:
    @OneToMany(mappedBy="parent", fetch=FetchType.EAGER)
    private List<Category> children;


Thank you very much.


Top
 Profile  
 
 Post subject:
PostPosted: Sun Feb 25, 2007 2:19 pm 
Regular
Regular

Joined: Wed Aug 25, 2004 7:40 pm
Posts: 65
If you definite the eager fetch mode, the children will be fetched along with their parent. This approach is fine if you need to access to its children each time when you have the parent object. Othewise, it is better from the performance point of view to specify your HQL(s) on fetching the children when you need to get the children object as well. I can image that some entities in your application have the category object as their attribute. It can be a big performance hit if you set the fetch mode in the way.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 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.