I'm still in the learning phase of Hibernate; having gotten the basics down, I've moved on to figuring out some best practices.
The sample app them I'm using to explore Hibernate is a Swing app. I know that in the real world, most Hibernate apps I'll encounter will likely be web apps, but hey, this is how I decided to learn!
That being said, I figured I should approach my sample app as if I want to implement it correctly for what it is: a potentially-long-running desktop app.
A primary difference between my app and a typical web app is the lack of request/response cycles. So I feel like I'm approaching unchartered territory when it comes to managing my Sessions. In a webapp, it seems that typically one Session per request/response cycle would be used, with the Session being closed thereafter. Entities wouldn't tend to linger in memory for too long; instead, the request would cause them to be fetched from the database, and the response would [resent them to the user. Session done.
With my Swing app, though, my entities will stick around in memory for quite some time. I'm trying to follow the recommendations of my (web-app-oriented) tutorials, and closing my Sessions after doing something meaningful (e.g. reading from or writing to the database). But I find it hard to avoid certain errors. For example, at the moment I am experiencing this one:
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.me.movies.model.Movie#1]
when I call session.saveOrUpdate() on an existing Movie entity, that I had originally read from the database via an older, now-closed Session. I suspect that the new Session isn't aware that the Movie already exists, and thus is SAVEing rather than UPDATEing.
I've also been playing whack-a-mole with these guys:
org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
So with all that, does anyone have any best-practices for Hibernate Sessions with apps such as mine? Should I still be striving to close my Sessions after db reads/writes? Or should I consider the lifecycle of my Swing app to be equivalent to a session, and therefore open and reuse a single Hibernate Session for the life of my app?
Thanks in advance for any advice.