Session management using Hibernate in a Swing application

前端 未结 4 1832
天涯浪人
天涯浪人 2020-12-23 23:46

How do you do your Hibernate session management in a Java Desktop Swing application? Do you use a single session? Multiple sessions?

Here are a few references on the

4条回答
  •  臣服心动
    2020-12-24 00:33

    Don't use a single session. For everything but the smallest applications, it will grow, collecting outdated data and become slower and slower, since the dirty check needs to check every entity in the session.

    If you don't need/want lazy loading and tracking of changes by Hibernate, you can use short-lived sessions.

    But if you want to benefit from the power of Hibernate use the approach I described in my blog: http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/

    or in the German version:

    http://blog.schauderhaft.de/2007/12/17/hibernate-sessions-in-fat-client-anwendungen/

    AFAIK it is really the same approach described in the http://in.relation.to/Bloggers/HibernateAndSwingDemoApp but with a recommendation how to actually scope your session: On Session per Frame, with the exception of modal Frames which use the session of the parent Frame.

    Just make sure never to combine objects from different sessions. It will cause lots of trouble.

    In reply to Vladimirs update:

    • The cancel actually works extremely nice with my approach: throw away the session.
    • session.flush does not fix the problem of the evergrowing session when you work with a single session for the application. Of course with the approach, you describe you can work with short-lived sessions which should work ok. BUT
    • you lose a lot: lazy loading only works with attached objects, automatic detection of dirty objects. If you work with detached objects (or objects that aren't entities at all) you have to do this yourself.

提交回复
热议问题