-
26-10-2019 - |
質問
私はこれを試しました:
@RequestMapping(method = RequestMethod.GET, value = "/getmainsubjects")
@ResponseBody
public JSONArray getMainSubjects( @RequestParam("id") int id) {
List <Mainsubjects> mains = database.getMainSubjects(id, Localization.getLanguage());
JSONArray json = JSONArray.fromObject(mains);
return json;
}
getmainsubjects.html?id = 1を呼び出すと、エラーが表示されます。
net.sf.json.jsonexception:org.hibernate.lazyInitializationException:役割のコレクションを怠lazに初期化できませんでした:fi.utu.tuha.domain.mainsubjects.aiforms、セッションまたはセッションは閉じられませんでした
直し方?
解決
問題は、モデルオブジェクトの主観的な被験者には、いくつかの関連性(オネトマ、多くのものなどによって構築されたもの)、リスト(永続的なバッグ)、セット、またはこのようなもの(コレクション)が怠lazであることです。つまり、結果セットの初期化後、MainSubjectsは実際のコレクションオブジェクトを指し示しず、代わりにプロキシを意味します。レンダリング、このコレクションへのアクセス中、Hibernateはプロキシを使用してデータベースから値を取得しようとします。しかし、この時点では、セッションが開いていません。そのため、この例外を取得します。
このように、フェッチング戦略を熱心に(注釈を使用する場合)に設定することができます:@onetomany(fetch = fetchtype.eeger)
この方法では、複数の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();
}