-->
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.  [ 3 posts ] 
Author Message
 Post subject: lazy initialization problem, Please help
PostPosted: Fri Feb 19, 2010 4:17 am 
Newbie

Joined: Thu Feb 18, 2010 8:35 am
Posts: 3
Hi All,
I have these two access classes
Code:

package comm.dao;

import org.hibernate.*;
import javax.persistence.*;
import comm.utils.*;


import org.apache.commons.logging.*;
import org.hibernate.criterion.Restrictions;
import org.hibernate.Query;


import comm.models.*;
import java.util.List;


public class AuthorDAO {

    public Author SaveAuthor(Author author) {

        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        List<Author> testList = session.createCriteria(Author.class).add(Restrictions.eq("email", author.getEmail())).list();
        Author myAuthor;
        if (testList != null && testList.size() > 0) {
            myAuthor = testList.get(0);
        } else {
            myAuthor = author;
           
        }
        session.saveOrUpdate(myAuthor);
        tx.commit();
        session.flush();
        session.close();
        return myAuthor;
    }

    public List<Author> ListAuthors(int intStartOffset, int endOffset) {

        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction newTransaction = session.beginTransaction();
        Query q = session.createQuery("from Author");
        q.setFirstResult(intStartOffset);
        q.setMaxResults(endOffset);
        List<Author> list = q.list();
        newTransaction.commit();
        session.close();
        return list;
    }

    public List<Author> ListAuthors() {

        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction newTransaction = session.beginTransaction();
        Query q = session.createQuery("from Author");
        List<Author> list = q.list();
        newTransaction.commit();
        session.close();
        return list;

    }
}


And
Code:

package comm.dao;

import org.hibernate.*;
import javax.persistence.*;
import comm.utils.*;


import org.apache.commons.logging.*;
import org.hibernate.criterion.Restrictions;
import org.hibernate.Query;


import comm.models.*;
import java.util.List;

public class MessageDAO {

    public Message SaveMessage(Message message) {

        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        session.saveOrUpdate(message);
        tx.commit();
        session.flush();
        session.close();
        return message;
    }

    public List<Message> ListMessages(int intStartOffset, int endOffset) {

        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction newTransaction = session.beginTransaction();
        Query q = session.createQuery("from Message");
        q.setFirstResult(intStartOffset);
        q.setMaxResults(endOffset);
        List<Message> list = q.list();
        newTransaction.commit();
        session.close();
        return list;
    }
    public List<Message> ListMessages() {

        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction newTransaction = session.beginTransaction();
        Query q = session.createQuery("from Message");
        List<Message> list = q.list();
        newTransaction.commit();
        session.close();
        return list;
    }
}



And two Model classes mapped to hibernate
Code:

package comm.models;

import java.io.Serializable;
import java.util.Date;
import java.util.Set;


public class Author implements Serializable {

    private Long id;
    private String name;
    private String nick;
    private String password;
    private String email;
    private String address;
    private String selftext;
    private Date dateOfBirth;
    private Date dateOfJoin;
    private Set<Asset> assets;
    private Set<Message> messages;

    public Author() {
    }

    public Set<Asset> getAssets() {
        return assets;
    }

    public void setAssets(Set<Asset> assets) {
        this.assets = assets;
    }

    public Set<Message> getMessages() {
        return messages;
    }

    public void setMessages(Set<Message> messages) {
        this.messages = messages;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public Date getDateOfJoin() {
        return dateOfJoin;
    }

    public void setDateOfJoin(Date dateOfJoin) {
        this.dateOfJoin = dateOfJoin;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getNick() {
        return nick;
    }

    public void setNick(String nick) {
        this.nick = nick;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSelftext() {
        return selftext;
    }

    public void setSelftext(String selftext) {
        this.selftext = selftext;
    }
}



and

Code:

package comm.models;

import java.io.Serializable;

public class Message implements Serializable {

    private Long id;   
    private String text;
    private Author messageAuthor;
    private Asset messageAsset;

    public Message() {
    }

    public Long getId() {
        return id;
    }

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

    public Asset getMessageAsset() {
        return messageAsset;
    }

    public void setMessageAsset(Asset messageAsset) {
        this.messageAsset = messageAsset;
    }

    public Author getMessageAuthor() {
        return messageAuthor;
    }

    public void setMessageAuthor(Author messageAuthor) {
        this.messageAuthor = messageAuthor;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

}


and in my servlet I have written this method

Code:
    private List dosomething() {



        MessageDAO messageAccess = new MessageDAO();
        AuthorDAO authorAccess = new AuthorDAO();
        String authEmail = "test@test.com";
        Author myAuthor = new Author();
        myAuthor.setName("Supratim");
        myAuthor.setDateOfBirth(new Date());
        myAuthor.setEmail(authEmail);
        myAuthor.setDateOfJoin(new Date());
        myAuthor.setNick("sup");
        myAuthor.setPassword("testpass");
        myAuthor = authorAccess.SaveAuthor(myAuthor);
       
        Message message = new Message();
        message.setText("Test Message");
        message.setMessageAuthor(myAuthor);
        messageAccess.SaveMessage(message);
       

        List<comm.models.Message> messages = messageAccess.ListMessages(0, 10);
        logger.info(messages.size() + " message(s) found:");
       
        System.out.println("Total Messages by "+myAuthor.getEmail()+"::"+myAuthor.getMessages().size());       

        return messages;
    }


Problem is when I call myAuthor.getMessages().size() .. it fails lazy loading.. saying

Code:
SEVERE: failed to lazily initialize a collection of role: comm.models.Author.messages, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: comm.models.Author.messages, no session or session was closed


How can I fix this problem.
Thanks in advance.


Top
 Profile  
 
 Post subject: Re: lazy initialization problem
PostPosted: Fri Feb 19, 2010 5:33 am 
Newbie

Joined: Mon Feb 15, 2010 3:09 pm
Posts: 7
Acctually the error message you are seeing is quite clear - the session is closed, thats how you designed your access DAO. You didn't post the mappings but I assume you didn't change any of hibernates defaults - and for Set relations lazy loading is used by default.

When loading the author instance hibernate simply inserts a proxy instance instead of the authors message set. This proxy will load the message set as soon as you need it - however it needs an active session but the session has been closed by the DAO.

You either need to modify the mapping to eagerly load the sets of your relations, bypassing most of hibernates optimization techniques. Better keep the session open - depends on the other environment where your code will execute. If this is going to be a web application consider using the OpenSessionInView pattern.

Google is your friend ;-)


Top
 Profile  
 
 Post subject: Re: lazy initialization problem, Please help
PostPosted: Fri Feb 19, 2010 2:30 pm 
Newbie

Joined: Wed Jan 27, 2010 8:16 am
Posts: 3
OpenSessionInView enough in 90% of the cases, but when the tree is too complex and your objects exists for more then one request, you can make deep clones when necessary(take care, the clones can lower the performance since all lazy objects will be loaded at once).

But in my opinion we should not worry about it, hibernate could have a alternatiev solution for this problem.
An idea is that the PersistentBag or Proxy have a reference to the factory that created its session and when the session is closed it creates a new session just for the fetch.

Good luck


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