Lazy Initialization Error in Java

0 votes

I get the following exception:

Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
    at sei.persistence.wf.entities.Element_$$_jvstc68_47.getNote(Element_$$_jvstc68_47.java)
    at JSON_to_XML.createBpmnRepresantation(JSON_to_XML.java:139)
    at JSON_to_XML.main(JSON_to_XML.java:84)

when I try to call from main the following lines:

Model subProcessModel = getModelByModelGroup(1112);
System.out.println(subProcessModel.getElement().getNote());

I implemented the getModelByModelGroup(int modelgroupid) method firstly like this :

    public static Model getModelByModelGroup(int modelGroupId, boolean openTransaction) {

        Session session = SessionFactoryHelper.getSessionFactory().getCurrentSession();     
        Transaction tx = null;

        if (openTransaction)
            tx = session.getTransaction();

        String responseMessage = "";

        try {
            if (openTransaction)            
                tx.begin();
            Query query = session.createQuery("from Model where modelGroup.id = :modelGroupId");
            query.setParameter("modelGroupId", modelGroupId);
            @SuppressWarnings("unchecked")
            List<Model> modelList = (List<Model>)query.list(); 
            Model model = null;
            // Cerco il primo Model che è in esercizio: idwf_model_type = 3
            for (Model m : modelList)
                if (m.getModelType().getId() == 3) {
                    model = m;
                    break;
                }

            if (model == null) {
                Object[] arrModels = modelList.toArray();
                if (arrModels.length == 0) 
                    throw new Exception("Non esiste ");

                model = (Model)arrModels[0];
            }

            if (openTransaction)
                tx.commit();
            return model;

        } catch(Exception ex) {
            if (openTransaction)
                tx.rollback();
            ex.printStackTrace();
            if (responseMessage.compareTo("") == 0)
                responseMessage = "Error" + ex.getMessage();
            return null;        
        }

and got the exception. Then a friend suggested me to always test the session and get the current session to avoid this error. So i did this:

public static Model getModelByModelGroup(int modelGroupId) {

        Session session = null;
        boolean openSession = session == null;
        Transaction tx = null;
        if (openSession){
          session = SessionFactoryHelper.getSessionFactory().getCurrentSession();   
            tx = session.getTransaction();
        }
        String responseMessage = "";

        try {
            if (openSession)            
                tx.begin();
            Query query = session.createQuery("from Model where modelGroup.id = :modelGroupId");
            query.setParameter("modelGroupId", modelGroupId);
            @SuppressWarnings("unchecked")
            List<Model> modelList = (List<Model>)query.list(); 
            Model model = null;
            for (Model m : modelList)
                if (m.getModelType().getId() == 3) {
                    model = m;
                    break;
                }

            if (model == null) {
                Object[] arrModels = modelList.toArray();
                if (arrModels.length == 0) 
                    throw new RuntimeException("Non esiste");

                model = (Model)arrModels[0];

            if (openSession)
                tx.commit();
            return model;

        } catch(RuntimeException ex) {
            if (openSession)
                tx.rollback();
            ex.printStackTrace();
            if (responseMessage.compareTo("") == 0)
                responseMessage = "Error" + ex.getMessage();
            return null;        
        }

    }

but still get the same error. I have been reading a lot for this error and found some possible solutions. One of them was to set lazyLoad to false but I am not allowed to do this thats why i was suggested to control the session

Jan 14 in Java by Sushmita
• 6,820 points
70 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes

What is wrong here is that your session management configuration is set to close session when you commit transaction. Check if you have something like:

<property name="current_session_context_class">thread</property> 

in your configuration.

In order to overcome this problem you could change the configuration of session factory or open another session and only than ask for those lazy loaded objects. But what I would suggest here is to initialize this lazy collection in getModelByModelGroup itself and call:

Hibernate.initialize(subProcessModel.getElement());

when you are still in active session.

And one last thing. A friendly advice. You have something like this in your method:

            for (Model m : modelList)
            if (m.getModelType().getId() == 3) {
                model = m;
                break;
            }

Please insted of this code just filter those models with type id equal to 3 in the query statement just couple of lines above.

Some more reading:

session factory configuration

problem with closed session

answered Jan 14 by developer_1
• 3,220 points

Related Questions In Java

0 votes
2 answers

One line initialization of an ArrayList object in Java

In Java 8 or earlier: List<String> string = ...READ MORE

answered Jul 26, 2018 in Java by samarth295
• 2,190 points
80 views
0 votes
1 answer

Static Map initialization in Java

I would suggest you to use the ...READ MORE

answered May 4, 2018 in Java by Akrati
• 3,150 points
3,739 views
0 votes
1 answer

Difference between FetchType LAZY and EAGER in Java Persistence API?

Sometimes you have two entities and there's ...READ MORE

answered Dec 5, 2018 in Java by Daisy
• 8,020 points
250 views
0 votes
1 answer

Compiling error in Java

Generally the file name and the class ...READ MORE

answered Mar 7 in Java by Priyaj
• 56,120 points
7 views
+1 vote
10 answers

Hibernate hbm2ddl.auto possible values and their uses

hibernate.hbm2ddl.auto (e.g. none (default value), create-only, drop, create, create-drop, validate, and update) Setting to perform SchemaManagementTool actions automatically as ...READ MORE

answered Dec 7, 2018 in Java by Shuvodip
4,134 views
0 votes
1 answer

Hibernate show real SQL

If you want to see the SQL ...READ MORE

answered Jul 5, 2018 in Java by Sushmita
• 6,820 points
54 views
0 votes
1 answer

object references an unsaved transient instance - save the transient instance before flushing

You should add cascade="all" (if using xml) ...READ MORE

answered Sep 26, 2018 in Java by parth295
• 4,590 points
1,869 views
0 votes
1 answer

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association?

The annotation @JoinColumn indicates that this entity is the owner of ...READ MORE

answered Oct 18, 2018 in Java by Sushmita
• 6,820 points
1,159 views
0 votes
1 answer

Dagger error in Java

What's going on? Have a good look at ...READ MORE

answered Feb 11 in Java by developer_1
• 3,220 points
29 views
0 votes
3 answers

Check if a String is numeric in Java

Java 8 Lambda Expression is used: String someString ...READ MORE

answered Sep 3, 2018 in Java by Daisy
• 8,020 points
443 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.