D
D
ddddd tttt2017-01-12 18:13:20
Java
ddddd tttt, 2017-01-12 18:13:20

How to fix LazyInitializationException?

package display;

import org.hibernate.Hibernate;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import static javax.persistence.GenerationType.IDENTITY;

/**
 * Created by D$DA$E on 11.01.2017.
 */
@Entity
@Table(name = "contact")
@NamedQueries({
        @NamedQuery(name = "Contact.findAllWithDetail",
                query = "select distinct c from Contact c " +
                        "left join fetch c.contactTelDetails t " +
                        "left join fetch c.hobbies h ORDER BY c.id")
                ,
        @NamedQuery(name ="Contact",query = "from Contact c")}
)
public class Contact implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private Long id;

    @Version
    @Column(name = "VERSION")
    private int version;

    @Column(name = "FIRST_NAME")
    private String firstName;

    @Column(name = "LAST_NAME")
    private String lastName;

    @Temporal(TemporalType.DATE)
    @Column(name = "BIRTH_DATE")
    private Date birthDate;

    @OneToMany(mappedBy = "contact", cascade = CascadeType.ALL,
            orphanRemoval = true)
    private Set<ContactTelDetail> contactTelDetails;

    @ManyToMany
    @JoinTable(name = "contact_hobby_detail",
            joinColumns = @JoinColumn(name = "CONTACT_ID"),
            inverseJoinColumns = @JoinColumn(name = "HOBBY_ID"))
    private Set<Hobby> hobbies;

    public Long getid()
    {return this.id;}

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

    public Set<ContactTelDetail> getContactTelDetails()
    {
        return this.contactTelDetails;
    }
    public void setContactTelDetails(Set<ContactTelDetail> contactTelDetails)
    {this.contactTelDetails = contactTelDetails;}

    public void addContactTelDetail(ContactTelDetail contactTelDetail) {
     contactTelDetail.setContact(this);
     getContactTelDetails().add(contactTelDetail);
    }

    public void removeContactTelDetail(ContactTelDetail contactTelDetail)
    {getContactTelDetails().remove(contactTelDetail);}


    public int getVersion ()
    {return this.version;}

    public void setVersion ( int version)
    {this.version = version;}


    public String getFirstName()
    {return this.firstName;}

    public void setFirstName(String firstName)
    {this.firstName = firstName;}


    public String getLastName()
    {return this.lastName;}

    public void setLastName(String lastName)
    {this.lastName = lastName;}


    public Date getBirthDate()
    {return this.birthDate;}

    public void setBirthDate (Date birthDate)
    {this.birthDate = birthDate;}

    public Set<Hobby> getHobbies()
    {
        return this.hobbies;
    }
    public void setHobbies(Set<Hobby> hobbies)
        {this.hobbies = hobbies;}

    public String toString() {
                return "Contact - Id: " + id + ", First name: " + firstName
                        + ", Last name: " + lastName + ", Birthday: " + birthDate;}

}

package session;

import display.Contact;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;

/**
 * Created by D$DA$E on 11.01.2017.
 */
@Transactional
@Repository("contactDao")
public class ContactDaoImpl implements ContactDao {
    private static final Log LOG = LogFactory.getLog(ContactDaoImpl.class);
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory()
    { return sessionFactory;}
    @Resource(name="sessionFactory")
    public void setSessionFactory(SessionFactory sessionFactory)
    {this.sessionFactory = sessionFactory;}

    @Override
    @Transactional(readOnly=true)
    public List<Contact> findAll(){
       return sessionFactory.getCurrentSession().getNamedQuery("Contact").list();
    }

    @Override
    @Transactional(readOnly=true)
    public List<Contact> findAllWithDetail() {
        return sessionFactory.getCurrentSession().
                getNamedQuery("Contact.findAllWithDetail").list();
    }

    @Override
    public Contact findByid(Long id) {
        return null;
    }

    @Override
    public Contact save(Contact contact) {
        return null;
    }

    @Override
    public void delete(Contact contact) {

    }

package test;

import display.Contact;
import display.ContactTelDetail;
import display.Hobby;
import org.springframework.context.support.GenericXmlApplicationContext;
import session.ContactDao;

import java.util.List;

/**
 * Created by D$DA$E on 12.01.2017.
 */
public class SpringHibernateSample {
    public static void main (String [] args) {
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
        ctx.load("config/app-context-annotation.xml");
        ctx.refresh();
        ContactDao contactDao = ctx.getBean("contactDao", ContactDao.class);
        listContacts(contactDao.findAll());
    }
    private static void listContacts(List<Contact> contacts) {
        System.out.println("");
        System.out.println("Listing contacts without details:");
        for (Contact contact : contacts) {
            System.out.println(contact);

            if ((contact.getContactTelDetails()) != null) {   
          for (ContactTelDetail contactTelDetail : contact.getContactTelDetails()) //<<<<Здесь ошибка 
                {
                    System.out.println(contactTelDetail);
                }
            }

            if (contact.getHobbies() != null) {
                for (Hobby hobby : contact.getHobbies())    //<<<<Здесь ошибка 
                {
                    System.out.println(hobby);
                }
            }

            System.out.println();
        }
    }
}

Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: display.Contact.contactTelDetails, could not initialize proxy - no Session
What are the fixes?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
aol-nnov, 2017-01-13
@aol-nnov

(finger up) open session in view pattern?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question