In Hibernate, a common error faced by lots of developer is “org.hibernate.LazyInitializationException: could not initialize proxy – no Session“. In lots of forum the answer is no answer and most of forum have answer but there is no explanation for the beginners.
First, Lets reproduce this error in Hibernate.
Assume that Hibernate configuration (hibernate.cfg.xml) and mapping file is already written.
Consider below snap of code and assume that function is written in class “DBManager”.
public List<ChatMessage> getMessages() { List<ChatMessage> MessageList = new ArrayList<ChatMessage>(); Configuration cf = new Configuration().configure(); SessionFactory factory = cf.buildSessionFactory(); Session session = null; try { session = factory.openSession(); String SQL_QUERY = "from ChatMessage c"; Query query = session.createQuery(SQL_QUERY); Iterator<ChatMessage> it = query.iterate(); while (it.hasNext()) { ChatMessage c = it.next(); MessageList.add(c); //If below line is commented then code throws an error //System.out.println("In Manager - Msg - "+c.getMessage()); } } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } return MessageList; }
In above code, i am trying to fetch the collection of class “ChatMessage”. In while loop, simply i am adding the object in ArrayList and at the end i am returning the List. Check that i have commented the SOP statement at the end of while loop.
Lets consider that other class is invoking this code. Code snap of other class is:
List<ChatMessage> msgList = dbManager.getMessages(); System.out.println(" Size : "+msgList.size()); for(ChatMessage chatMsg : msgList) { out.println(olMsg+"<span style='background:#"+colorCode+"'>"+chatMsg.getUserName()+"</span>"+chatMsg.getMessage()+"<br/><br/>"); }
Whenever this code executes, it will throw an error inside for loop at “chatMsg.getUserName()” because the lazy loading is true by default and as error also describes this. The best solution is to make “lazyLoad=false” in configuration file. The code will then run perfect, but why this error did come?
This error means that you’re trying to access a lazily-loaded property or collection, but the hibernate session is closed or not available . Lazy loading in Hibernate means that the object will not be populated (via a database query) until the property/collection is accessed in code. Hibernate accomplishes this by creating a dynamic proxy object that will hit the database only when you first use the object. In order for this to work, your object must be attached to an open Hibernate session throughout it’s lifecycle.
When we uncomment the SOP statement, program runs successfully, because it hits the object and therefore it initializes itself through hibernate session.
Leave a Reply