Sunday, 10 May 2015

[ERROR] Nested in org.springframework.web.util.NestedServletException: Request p rocessing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: 'xxxxxxxx', no session or session was closed: org.hibernate.LazyInitializationException: failed to lazily initialize a collect ion of role: 'xxxxxxxx', no session or session was c losed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitia lizationException(AbstractPersistentCollection.java:383) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitia lizationExceptionIfNotConnected(AbstractPersistentCollection.java:375) at org.hibernate.collection.AbstractPersistentCollection.initialize(Abst ractPersistentCollection.java:368) at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPe rsistentCollection.java:111) at org.hibernate.collection.PersistentBag.iterator(PersistentBag.java:27 2) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr ite(CollectionTypeAdapterFactory.java:95) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr ite(CollectionTypeAdapterFactory.java:60) at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(Typ eAdapterRuntimeTypeWrapper.java:68) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(Re flectiveTypeAdapterFactory.java:89) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.wr ite(ReflectiveTypeAdapterFactory.java:195) at com.google.gson.internal.bind.ObjectTypeAdapter.write(ObjectTypeAdapt er.java:107) at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(Typ eAdapterRuntimeTypeWrapper.java:68) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr ite(CollectionTypeAdapterFactory.java:96) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr ite(CollectionTypeAdapterFactory.java:60) at com.google.gson.Gson.toJson(Gson.java:593) at com.google.gson.Gson.toJson(Gson.java:572) at com.google.gson.Gson.toJson(Gson.java:527) at com.google.gson.Gson.toJson(Gson.java:507) at net.demo.contact.controller.ContactController.getAddressList(ContactC ontroller.java:64) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl. java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces sorImpl.java:43)

[ERROR] Nested in org.springframework.web.util.NestedServletException: Request p
rocessing failed; nested exception is org.hibernate.LazyInitializationException:
 failed to lazily initialize a collection of role: net.demo.contact.form.Address
.contacts, no session or session was closed:
org.hibernate.LazyInitializationException: failed to lazily initialize a collect
ion of role: net.demo.contact.form.Address.contacts, no session or session was c
losed
        at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitia
lizationException(AbstractPersistentCollection.java:383)
        at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitia
lizationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
        at org.hibernate.collection.AbstractPersistentCollection.initialize(Abst
ractPersistentCollection.java:368)
        at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPe
rsistentCollection.java:111)
        at org.hibernate.collection.PersistentBag.iterator(PersistentBag.java:27
2)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr
ite(CollectionTypeAdapterFactory.java:95)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr
ite(CollectionTypeAdapterFactory.java:60)
        at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(Typ
eAdapterRuntimeTypeWrapper.java:68)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(Re
flectiveTypeAdapterFactory.java:89)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.wr
ite(ReflectiveTypeAdapterFactory.java:195)
        at com.google.gson.internal.bind.ObjectTypeAdapter.write(ObjectTypeAdapt
er.java:107)
        at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(Typ
eAdapterRuntimeTypeWrapper.java:68)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr
ite(CollectionTypeAdapterFactory.java:96)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.wr
ite(CollectionTypeAdapterFactory.java:60)
        at com.google.gson.Gson.toJson(Gson.java:593)
        at com.google.gson.Gson.toJson(Gson.java:572)
        at com.google.gson.Gson.toJson(Gson.java:527)
        at com.google.gson.Gson.toJson(Gson.java:507)
        at net.demo.contact.controller.ContactController.getAddressList(ContactC
ontroller.java:64)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.
invokeHandlerMethod(HandlerMethodInvoker.java:174)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandle
rAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandle
rAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(Dispatch
erServlet.java:771)


SOLUTION

You are getting this error because, when you are trying to return a data in JSON or GSON from controller. you are returning the object which is provided by the service. and this object contains dependencies of other objects like if we have used any relationships (@OneToMany or @ManyToMany or @ManyToOne or @OneToOne ) in the object so when we are converting this object to JSON or GSON it is going into that all dependencies to get the data. so we are getting this error of  nested exception is org.hibernate.LazyInitializationException.

to solve this you can do below thing.

STEP - 1 ) Create SIMPLE POJO class with all the fields which you want in your JSON data like..

  I have one model which i want to return named Contactas below but we have used we have used @ManyToOne dependency in this so when we will try to return it directly we will get above error. so now see the next step.

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="CONTACTS")
public class Contact implements Serializable  {
    private static final long serialVersionUID = 1L;
   
    @Id
    @Column(name="ID")
    @GeneratedValue
    private Integer id;
   
    @Column(name="FIRSTNAME")
    private String firstname;

    @Column(name="LASTNAME")
    private String lastname;

    @Column(name="EMAIL")
    private String email;
   
    @Column(name="TELEPHONE")
    private String telephone;
   
    @ManyToOne
    private Address address;
   
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public String getEmail() {
        return email;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getFirstname() {
        return firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
   
}

STEP-2 ) Create simple POJO class of model but without hibernate annotation like.

public class ContactPOJO  {
    private Integer id;
   
    private String firstname;

    private String lastname;

    private String email;
   
    private String telephone;
   
    private Address address;
   
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public String getEmail() {
        return email;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getFirstname() {
        return firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
   
}

STEP - 3 ) Now use this class to return the data as i have used below.

  try {
            Gson gson=new Gson();
            Contact c=contactService.getContactById(contactId);  //////Object which are receiving from service

            ContactPOJO wc=new ContactPOJO();                   ///// Object we create to return in json formate
            wc.setId(c.getId());
            wc.setFirstname(c.getFirstname());
            wc.setLastname(c.getLastname());
            wc.setEmail(c.getEmail());
            wc.setTelephone(c.getTelephone());
            wc.setAddressId(c.getAddress().getId());

            response.getWriter().write(gson.toJson(wc));

        } catch (IOException e) {
            e.printStackTrace();
        }

STEP - 4 ) Now you will not get the error.

Please follow if you like this. contact me you need some help.