Reputation: 626
I am developing an application with Spring MVC , Hibernate and database MySQL Controller handle the request and response. Hibernate handles the database transaction.
My problem is when one or two access the service it works fine, but for more than that work fine for some time, but after that I get the error frequently lock time out
//My sample Controller code
@RequestMapping(value = "Bank", method = RequestMethod.GET)
public ResponseEntity<List<Bank>> getAllBank(@RequestHeader int data) {
try {
//My DAO implementation class for bank table
bankdao = new BankDAOImpl();
List<Bank> bank = bankdao.getAllBank(data);
return new ResponseEntity<List<Bank>>(bank, HttpStatus.OK);
} catch (HibernateException he) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
//My DAO implementation code
public List<Bank> getAllBank(int organizationId) throws HibernateException {
//I'm opening session in every function
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
session.beginTransaction();
Criteria criteria = session.createCriteria(Bank.class);
criteria.add(Restrictions.eq("organizationId", organizationId));
criteria.add(Restrictions.eq("deleteFlag", false));
criteria.addOrder(Order.asc("bankName"));
List<Bank> ls=criteria.list();
return ls;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.getTransaction().commit();
session.close();
}
That session causing the problem If I create a separate session factory for all functions instead of open a session
Will it solve my problem?
Upvotes: 1
Views: 162
Reputation: 19976
You shouldn't create a separate session factory for every method. Just open a session. May be a problem is your incorrect way of working with transactions. You should do it this way
public List<Bank> getAllBank(int organizationId) throws HibernateException {
//I'm opening session in every function
Session session = SessionFactoryUtil.getSessionFactory().openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Criteria criteria = session.createCriteria(Bank.class);
criteria.add(Restrictions.eq("organizationId", organizationId));
criteria.add(Restrictions.eq("deleteFlag", false));
criteria.addOrder(Order.asc("bankName"));
List<Bank> ls=criteria.list();
tx.commit();// commit here
return ls;
} catch (Exception e) {
e.printStackTrace();
if (tx != null) {
tx.rollback();// rollback here
}
return null;
} finally {
session.close();
}
}
May be a problem is your SessionFactoryUtil
. It would be interesting to see it.
Upvotes: 2