Reputation: 55
I am fairly new to Hibernate. I am trying to understand sessions and transactions using the example below. I have an event management system. I have an entity called Event, and a user can edit an Event. Should I save a session as an instance variable in the service class and use it to do multiple Transactions in different methods ? I also would like to use it as a cache. Where should session object be stored ? Or how to best achieve what I am trying to do below - I have two transactions - first will fetch as event object and second needs to edit it and save it to the database.
ServiceClass {
Session session ;
Constructor () {
session = sessionFactory.getSession();
}
//First transaction
public Event getEvent() {
begin new Transaction on session.
Fetch new Event object
End new transacton
return event; //to display to user
}
//Second transaction
public void editEvent(String newName, Date newDate) {
begin Transaction
Obtain the Event object from the session which was result of First transaction above
event.setName(newName); //This should be in persistent state and affect the database
event.setDate(newDate);
end Transaction
}
}
Thank you so much in advance :)
Upvotes: 1
Views: 211
Reputation: 73
You need to consider the session the transaction. If your ServiceClass is used in multi-threaded environment (such as Servlets) then specifying it in a field will cause threading issues. To avoid this problem, put the session creation in the editEvent() method, which should:
Upvotes: 1