问题是,您的模型对象 Mainsubjects 有一些关联(由 OneToMany、ManyToOne 等构建)、列表(PersistentBags)、集合或类似这样的东西(集合),它们是延迟初始化的。这意味着,在结果集初始化之后,Mainsubjects 不会指向实际的集合对象,而是代理。在渲染、访问这个集合时,hibernate 尝试使用代理从数据库中获取值。但此时没有会话打开。出于这个原因,你会得到这个例外。
您可以将获取策略设置为 EAGER(如果您使用注释),如下所示:@OneToMany(fetch=FetchType.EAGER)
在这种方法中,您必须注意,您不能允许多个 PersistentBag 急切地初始化。
或者您可以使用 OpenSessionInView 模式,这是一个 servlet 过滤器在控制器处理您的请求之前打开一个新会话,并在您的 Web 应用程序响应之前关闭:
public class DBSessionFilter implements Filter {
private static final Logger log = Logger.getLogger(DBSessionFilter.class);
private SessionFactory sf;
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
log.debug("Starting a database transaction");
sf.getCurrentSession().beginTransaction();
// Call the next filter (continue request processing)
chain.doFilter(request, response);
// Commit and cleanup
log.debug("Committing the database transaction");
sf.getCurrentSession().getTransaction().commit();
} catch (StaleObjectStateException staleEx) {
log.error("This interceptor does not implement optimistic concurrency control!");
log.error("Your application will not work until you add compensation actions!");
// Rollback, close everything, possibly compensate for any permanent changes
// during the conversation, and finally restart business conversation. Maybe
// give the user of the application a chance to merge some of his work with
// fresh data... what you do here depends on your applications design.
throw staleEx;
} catch (Throwable ex) {
// Rollback only
ex.printStackTrace();
try {
if (sf.getCurrentSession().getTransaction().isActive()) {
log.debug("Trying to rollback database transaction after exception");
sf.getCurrentSession().getTransaction().rollback();
}
} catch (Throwable rbEx) {
log.error("Could not rollback transaction after exception!", rbEx);
}
// Let others handle it... maybe another interceptor for exceptions?
throw new ServletException(ex);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
log.debug("Initializing filter...");
log.debug("Obtaining SessionFactory from static HibernateUtil singleton");
sf = HibernateUtils.getSessionFactory();
}