Announcement Announcement Module
No announcement yet.
Should I close the session per operation? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Should I close the session per operation?

    package org.nirvana.jswiki.dao.impl;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.nirvana.jswiki.dao.BaseDAO;
    public class BaseDAOImpl implements BaseDAO {
    	protected SessionFactory sessionFactory;
    	public void create(Object o) {
    		Session session = sessionFactory.getCurrentSession();;
    	public void save(Object o) {
    		Session session = sessionFactory.getCurrentSession();;
    	public void update(Object o) {
    		Session session = sessionFactory.getCurrentSession();
    	public void saveOrUpdate(Object o) {
    		Session session = sessionFactory.getCurrentSession();
    	public SessionFactory getSessionFactory() {
    		return sessionFactory;
    	public void setSessionFactory(SessionFactory sessionFactory) {
    		this.sessionFactory = sessionFactory;
    I wrote my BaseDAO, and if I closed the session in each method, and following Test would failure.
    		UserDAO dao = (UserDAO) ctx.getBean("userDAOProxy");
    		User u = dao.retriveByName("Nicholas");
    		u = new User();
    		u.setEmail("[email protected]");;
    		assertEquals("Helen", u.getName());
    If I did not close the session, this Test would be OK.
    Does Spring manage per sesson out-of-box?[/code]

  • #2
    We recommend using the HibernateTemplate provided by Spring.


    • #3
      How about implementating DAOs based on plain on Hibernate3 API?
      It said in Spring-Refernce chatper 11.2.5, I found that feature amazing.


      • #4
        SessionFactory.getCurrentSession() can indeed be used to code DAOs against the plain Hibernate3 API. The main advantage of this is that you only rely on standard Hibernate API and don't have Spring dependencies in your DAOs. The main disadvantage is that such DAOs will throw plain HibernateException, not Spring's DataAccessException - which doesn't allow callers to handle exceptions in a generic manner. If the latter is important to you, use Spring's HibernateTemplate - which we generally recommend. See the ORM chapter in our reference manual for details.

        Note that such a getCurrentSession() call does not open a Session for each call: It just accesses the current transactional Session, whose lifecycle is managed by the current transaction. Hence, you don't need to close it: just get a reference to it and access it, leaving the lifecycle to the transaction manager (either Spring's HibernateTransactionManager or JTA).



        • #5
          Thank you for your explaination.
          Now I using OpenSessionInViewInterceptor for per request and everything is OK.