0

My web application uses ActiveJDBC. This ORM framework requires to open new DB connection with every new thread (and of course close it when the thread finishes). I am wondering if the best way to achieve this is to use a Web Filter.

if this is the case, where do I call Base.open()? the options are init() or doFilter(). also, if I plan to call Base.close() in destroy(), I need to know that indeed destroy() is always called at the thread termination, whether it is normal or abnormal.

EDIT: after reading about servlet filters, I now believe that the proper processing would be to open and close the connection in doFilter():

public void doFilter(final ServletRequest request, final ServletResponse response, FilterChain chain) throws IOException, ServletException { 
  Base.open();
  chain.doFilter(request,wrapper);
  Base.close(); 
} 

is this the correct way?

Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47

2 Answers2

1

Yes, this is the correct way of opening and closing a connection for ActiveJDBC in a web environment.

In addition to that, this is the right place to manage exceptions. For instance, you might want to manage transactions like this:

try{
  Base.openTransaction(); 
  chain.doFilter(request,wrapper);
  Base.commitTransaction(); 
}catch(Exception e){
  // log exception
  Base.rollbackTransaction();
}finally{
  Base.close();
}

Ultimately rather than dealing with Servlets, why not give ActiveWeb a spin? See more here: http://javalite.io/database_configuration

ipolevoy
  • 5,432
  • 2
  • 31
  • 46
0

This is the correct implementation however, to scale up your application you may want a database connection pooler in which case you will want to keep your connections alive even after you do your db operations.

Max Alexander Hanna
  • 3,388
  • 1
  • 25
  • 35