Hi,
based on what I've read on Internet to handle the error on "open session", I have created the HibernateFilter with the code below...
Just two questions :
[1] How hibernate retrieve the
good connection to close in that Filter as it can have many sessions opened?
[2] Is my design good enough? do you see some weakness compare to ohter filters? Is it enough robust for production environment?
Here is the interesting snippet needed to construct the HibernateFilter (It may help also some of us who wants a sample) :
Code:
[b][u]HibernateFilter.java[/u][/b]
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
// Call the next filter (continue request processing)
chain.doFilter(request, response);
} finally {
// No matter what happens, close the Session.
HibernateUtil.closeSession();
}
}
[b][u]MyStrutsAction.java[/u][/b]
Session session = HibernateUtil.currentSession();
Transaction transaction = session.beginTransaction();
//The comp_id on contact is stupid but just for sample with composite keys!
Query query = session.createQuery("from contact declarationsdsa where contact.comp_id.lastname=? and contact.comp_id.firstname=?");
query.setString(0,"Dupont");
query.setString(1,"Jean");
Iterator it = query.iterate();
Contact contact = null;
if(it.hasNext()) {
contact= (Contact) it.next();
}
request.setAttribute("contact",contact);
transaction.commit(); //TODO handle rollback
session.flush();
[b][u]web.xml[/u][/b]
<!-- HibernateFilter -->
<filter>
<filter-name>hibernateFilter</filter-name>
<display-name>Hibernate Filter</display-name>
<filter-class>org.mycompany.hibernate.HibernateFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
[b][u]MyJSP.java[/u][/b]
we can display contact.getComp_id().getLastname() without getting the error on "session and proxy"