問題は、モデルオブジェクトのMainsubjectsに、いくつかの関連付け(OneToMany、ManyToOneなどによって構築された)、リスト(PersistentBags)、セット、またはこのようなもの(Collection)があり、これらは遅延して初期化されることです。つまり、結果セットの初期化後、Mainsubjectsは実際のコレクションオブジェクトをポイントせず、代わりにプロキシをポイントします。レンダリング中、このコレクションにアクセスしている間、hibernateはプロキシを使用してデータベースから値を取得しようとします。しかし、この時点では、開いているセッションはありません。そのため、この例外が発生します。
次のように、フェッチ戦略をEAGER(アノテーションを使用する場合)に設定できます。@ OneToMany(fetch = FetchType.EAGER)
この方法では、熱心に初期化されたPersistentBagを複数許可することはできないことに注意する必要があります。
または、OpenSessionInViewパターンを使用できます。これは、サーブレットフィルターが、要求がコントローラーによって処理される前に新しいセッションを開き、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();
}