Spring wrappers were a good idea for Hibernate 2.x if you didn't want to write a few things yourself. With Hibernate3 you get:
- unchecked exceptions, no need to wrap
- typed exception hierarchy, not much practical use but nice in some situations
- auto flushing and auto closing of the Hibernate Session in JTA environments
- a lot more...
This is the only code you need to startup Hibernate, put it in any class you like (the static block is loaded once):
Code:
public static SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable e) {
throw new ExceptionInInitializerError(e);
}
}
Now open Sessions from this factory whenever you need, if you run with EJB Session beans they will be flushed and closed automatically when your container transaction ends.
Another common thing people do is the "Open Session in View" with the "ThreadLocal Session" pattern. Download CaveatEmptor from
http://caveatemptor.hibernate.org/ and have a look at the HibernateUtil class. It's about 50 lines of trivial code (open/close) around two ThreadLocal variables for the Session and Transaction that can be easily reduced to 25 if you don't need it verbose. Use some interceptor (e.g. from your web framework or from your EJB container) to handle the Session and Transaction in whatever scope you like.