I have following code in my application each time I want to do some action with hibernate:
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(obj); //or delete, update etc.
session.getTransaction().commit();
session.close();
This is of course not a good practice. What is the best way to access hibernate and not to have situation like this? Should I use some ‘Util’ class that contains static methods that do the same job? Maybe singleton is better? I also need to wrap this code in thread or SwingWorker in order not to freeze my GUI while accessing database.
Yes, that code is pretty bad.
it opens a transaction for every database access. This is inefficient, and probably incorrect (usually, an entire group of actions needs to be atomic. For instance consider
If load and save are in their own transactions, and some evil user buys 2 items at the same time, the following may happen:
so the user bought twice, but only paid once 😉
it does not finish the transaction if save() throws an exception. In fact, the transaction will remain open indefinitely, including all the locks it holds …
Complexities such as these are the reason most people demarcate transactions declaratively rather than reinventing a square wheel, for instance with Spring or EJB.