1

Currently i am using Hibernate, Spring and postgres as database in my application. Unfortunately the connection to the database is keep on increasing.

Every method in the DAO Implementation class is increasing the connection count. Below is the piece of code in DAO Impl.

@Autowired
    SessionFactory sessionFactory;

    /**
     * Used to save or update a SourceConfig.
     * 
     * @throws Exception
     */
    @Override
    @Transactional
    public Long saveOrUpdateSourceConfig(SourceConfig sourceconfig) {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
                .getRequest();
        HttpSession httpsession = request.getSession();

        try {

            session.saveOrUpdate(sourceconfig);
            session.flush();
            tx.commit();

        } catch (JDBCException e) {
            tx.rollback();
            String nextException = e.getSQLException().getNextException().getLocalizedMessage();
            e.printStackTrace();
            System.out.println("next version" + nextException);
        }
        Serializable id = session.getIdentifier(sourceconfig);
        return (Long) id;

    }

I am unable to use session.getcurrentsession() and always this returns as null and i am not closing the session anywhere in the DAOImpl.

Please your response will be highly appreciated.

Karthick88it
  • 601
  • 2
  • 12
  • 28
  • 1
    Since you are using @Transactional it seems you are having spring managed transaction. So don't open the session and start transaction by your self. let spring handle it. – Akshay Khopkar Apr 19 '17 at 09:35
  • @ Akshay Thanks for your swift response. Without opening new session or getting current session, Is it possible to saveorupdate. Pls correct me if i am wrong. – Karthick88it Apr 19 '17 at 09:38
  • you will need a session and transaction but opening and closing will be managed by spring for you. use getCurrentSession on session factory to get the session. transaction start/commit/rollback will be handled by spring for you. – Akshay Khopkar Apr 19 '17 at 09:44
  • If i use **session.getCurrentSession()** which results in "No Session found for current thread".. If i open the session then i can able to access it. My problem is if i close the session anywhere in daoImpl then i was not able to access the opensession anywhere in the whole DAOImpl class. – Karthick88it Apr 19 '17 at 09:52
  • have you enabled transaction manager in spring? if it is not then enable it as mention it here - [link] http://www.journaldev.com/2603/spring-transaction-management-jdbc-example [/link] – Akshay Khopkar Apr 19 '17 at 10:17

0 Answers0