We all know th standard way to access the Hibernate session using the SessionHolder*.
This is a basic abstract class(shown below) that will add the .add(), .update() and .delete() methods to your data objects.
Just extend this class by your Hibernate DTO like this:
public class Address extends BaseData
And then just after populating the new Address object, you write address.add().
try{ SessionHolder.currentSession().getSess().save(this); SessionHolder.currentSession().getSess().flush(); SessionHolder.endSession(); ex.printStackTrace(); Messenger.addFatalMessage(ex.getMessage(),ex.getMessage()); return StandardResults.FAIL; } return StandartResults.SUCCESS; } try { SessionHolder.currentSession().getSess().update(this); SessionHolder.currentSession().getSess().flush(); return StandartResults.SUCCESS; SessionHolder.endSession(); ex.printStackTrace(); Messenger.addFatalMessage(ex.getMessage(),ex.getMessage()); return StandardResults.FAIL; } } try { SessionHolder.currentSession().getSess().delete(this); SessionHolder.currentSession().getSess().flush(); return StandartResults.SUCCESS; } catch (HibernateException ex) { SessionHolder.endSession(); ex.printStackTrace(); Messenger.addFatalMessage(ex.getMessage(),ex.getMessage()); return StandardResults.FAIL; } } }
This particular class was designed to be used in a JSF web application. Hence, the return types for methods are String's and there is a reference to StandardResults and Messenger class.
Messenger class is a generic class to present the user with a message.
StandardResults is what it's name stands for.
Please note, this may be used in JSF tables and lists only in places where the data is changed rarely or not concurrently.
But placing this element in a column in a h:dataTable will work as intended:
Also on your edit form page, you may use it without any potential problems, like this:
And on your new entry form page similarly:
In the end this technique saves a lot of time, by removing the need to create add, update and remove mehtods in your JSF managed-beans for those simple and boring CRUD operations.
* - For those who don't: see here or in simple terms this thing holds the session for the current thread and context - in the example, the call SessionHolder.currentSession() is translated to HibernateUtil.getSessionFactory().getCurrentSession().

2 comments:
I don't think you should recommend this way of using hibernate: flushing your session after each save/update could really cause performance problems.
Just to note, the flush call was needed for instances where one entity was mapped to a view.
This is not proffered, but rather a workaround for that case.
Post a Comment