Intro
I’m bulding a REST web service using Hibernate and Jersey to supply JSON data to mobile clients. I have a general question about how to deal with Hibernate sessions internally. There are two different approaches(A,B) I’d like to discuss.
Approaches
A. Someone told me I should open a new session per user, let it open for the whole web session of the user and finally close this session after the user stopped using my web service. I was told it would be a better approach from the view of security and performance.
Though I’ve read that:
"Sessions are irrelevant" Common REST Mistakes, 6.
B. Right now I’m using a SessionFactory to open a session in my service classes and close this session immediately after a query is done. My web service is only using GET and POST requests. There is not PUT or DELETE. I don’t need any user authentication (like oAuth) to request data. Therefore I don’t think it’s necessary to use Transactions
Here is an Example of my Service class:
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query query = session.createQuery("from RoomEntity");
@SuppressWarnings("unchecked")
List<RoomEntity> list = (List<RoomEntity>) query.list();
session.close();
Questions
Would be great to hear your opinion about my following questions:
- What would be the best practice? Which approach do you follow?
- What do you think about the performance matter?
- What do you think about the security matter?
I don’t like A. It makes your service stateful and how do you know when a user has finished with your services anyway?
The general rule with Hibernate and web apps is to use a single session per http request. Most REST service GET requests map pretty simply to a single DB query as you have demonstrated with B, so this is the way to go.