我认为这个问题是因为对象正在装载fetch = FetchType.LAZY strategy
。你可能想了解what is Eager fetch and what is Lazy fetch.
基本上
LAZY =需要
EAGER时取=取立即
方案1(推荐):使用急于在Category类抓取策略:
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. */
}
你DAO看起来有点像这样:
public List<Project> getProjects(Category category) {
Session session = sessionFactory.openSession();
session.merge(category);
List<Project> projects = category.getProjects();
session.close()
return projects;
}
解决方案2:发送Session对象与类别类
这样,您将确保会话当你真正需要它来访问你的对象不是封闭的
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方法沿
public List<Project> getProjects(Category category, Session session) {
session.merge(category);
return category.getProjects();
}