0

I have the next method in DAO:

public List<Project> getProjects(Category category) {
        Session session = sessionFactory.openSession();
        session.merge(category);
        return category.getProjects();
    }

In my application Category is Entity. And Project also. Category has OneToMany relation to Project entity (table). Here I try to get all projects with the same category using this relation (I tried with direct SQL request - it works without problem). When I try to use this method in this way, I got exception

failed to lazily initialize a collection of role: data.Category.project,could not initialize proxy - no Session

I suppose this is because inside method Category is in detached state and I try to make in managed again but with merge command without success((( Or I am wrong. Is it possible to use such code? Not use direct SQL command.

ovod
  • 1,118
  • 4
  • 18
  • 33

1 Answers1

0

I think the problem would be because the objects are being loaded with fetch = FetchType.LAZY strategy. You may wanna learn about what is Eager fetch and what is Lazy fetch.

Basically

LAZY = fetch when needed

EAGER = fetch immediately

Solution 1 (Recommended): Use Eager Fetch strategy in your Category Class:

public class Category {
    ...
    ...
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    List<Projects> projects;
    ...
    ...
    
    //Getters and Setters
    
    /* P.S. - I don't know what's the actual code for your classes. 
    I just assumed it to be somewhat like this. Please post your code if you face 
    any further problem and I'll modify my answer accordingly. */
}

Your DAO would look somewhat like this:

public List<Project> getProjects(Category category) {
        Session session = sessionFactory.openSession();
        session.merge(category);
        List<Project> projects = category.getProjects();
        session.close()
        return projects;
}

Solution 2: Send Session object along with your category class

This way you would ensure that session isn't closed when you actually need it to access your objects

public void yourMethod() {
    //Declare Session in starting of your class where you're accessing the objects
    Session session = sessionFactory.openSession();
    Category category = new Category();
    ...
    ...
    List <Project> projects = getProjects(category, session);
    ...
    ...
    //Perform all of your operations here
    ...
    ...
    session.close(); //Close session at the end 
}

DAO method

public List<Project> getProjects(Category category, Session session) {
    session.merge(category);
    return category.getProjects();
}
Community
  • 1
  • 1
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71