you can call it as many times and anywhere you like once you get hold of your org.hibernate.SessionFactory. The getCurrentSession() method always returns the "current" unit of work.
Remember that we switched the configuration option for this mechanism to "thread" in our src/main/resources/hibernate.cfg.xml? Due to that setting,
the context of a current unit of work is bound to the current Java thread that executes the application.
When the transaction ends, either through commit or rollback, Hibernate automatically
unbinds the org.hibernate.Session from the thread and closes it for you. If you call
getCurrentSession() again,
you get a new org.hibernate.Session and can start a new unit of work.
The scope of a Hibernate org.hibernate.Session is flexible but you should never design your application to use a new Hibernate org.hibernate.Session for every database operation. Even though it is used in the following examples,
consider session-per-operation an anti-pattern
Remember that we switched the configuration option for this mechanism to "thread" in our src/main/resources/hibernate.cfg.xml? Due to that setting,
the context of a current unit of work is bound to the current Java thread that executes the application.
When the transaction ends, either through commit or rollback, Hibernate automatically
unbinds the org.hibernate.Session from the thread and closes it for you. If you call
getCurrentSession() again,
you get a new org.hibernate.Session and can start a new unit of work.
The scope of a Hibernate org.hibernate.Session is flexible but you should never design your application to use a new Hibernate org.hibernate.Session for every database operation. Even though it is used in the following examples,
consider session-per-operation an anti-pattern
- private List listEvents() {
- Session session = HibernateUtil.getSessionFactory().getCurrentSession();
- session.beginTransaction();
- List result = session.createQuery("from Event").list();
- session.getTransaction().commit();
- return result;
- }
No comments:
Post a Comment