我認爲這個問題是因爲對象正在裝載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();
}