I have openSessionInView
filter in web.xml.
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
And I have set allowCreate
property of HibernateDaoSupport to true
. Now for each database operation if I get the Session by getSession
and close the Session after transaction like:
public List<User> getAllUsers() {
Session session = getSession();
session.enableFetchProfile("USER-ROLE-PROFILE");
Transaction transaction = session.beginTransaction();
DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
List<User> users = criteria.getExecutableCriteria(session).list();
transaction.commit();
session.disableFetchProfile("USER-ROLE-PROFILE");
session.close();
return users;
}
then would this Session close create any problem in openSessionInView
?
Another question:
Is this a good way to do various hibernate operation? In the above code the entity User
has a fetch profile.
Thanks and regards.
if the getAllUsers() is the last thing to do in a request lifecycle, this approach could be acceptable. But if you want to do more database operations, then you have to open a new session, because you have closed it. Moreover, if you don't close your session, it will be closed by filter:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
...// sf is SessionFactory
sf.getCurrentSession().beginTransaction();
// Call the next filter (continue request processing)
chain.doFilter(request, response);
sf.getCurrentSession().getTransaction().commit();
...
}