Reputation: 2602
I have a Spring MVC App, it works fine, but now I inserted the service pattern and I don't know what is the the best way to treat my JDBC Connection inside my DAO.
I have an interceptor which creates a connection like this:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle: Abrindo Conexao BD");
conn = new ConnectionFactory().getConnection();
request.setAttribute("conn", conn);
return true;
}
So, after this, I get the connection in my controller(servlet) like this:
@RequestMapping("efetuaLogin")
public String efetuaLogin(Usuario usuario, HttpSession session, HttpServletRequest request) throws ServletException {
Connection conn = (Connection) request.getAttribute("conn");
if(new UsuarioDAO(conn).existeUsuario(usuario)){
session.setAttribute("usuarioLogado", usuario);
return "adm/main-adm";
}
return "redirect:loginForm";
}
Very simple, I pass the connection to DAO and everything works fine. But now I have the layer service.
Before: Controller > DAO
Now: Controller > Service > DAO
I don't want to pass my connection(conn) as a parameter to Service, and after Service to pass conn as a parameter to DAO. It's not seem a good way to do.
I thought, maybe to get the connection factory inside my DAO, but I am not sure, the interceptor still seems better way to manage it.
So, How would you make it? Sorry if it is a stupid question, but I don't want to make up nothing in this moment, just to follow what the people are doing to create a good boilerplate...
Upvotes: 1
Views: 1502
Reputation: 530
A couple of things.. you probably shouldn't even be touching the connection at any layer of the code except the DAO layer. The fact that your DAOs are using JDBC should be hidden from everyone else. Also, you're using Spring so you shouldn't be constructing your DAOs at all, let Spring handle that. You can get rid of the interceptor all together.
The least invasive change to your code would be for your interceptor to put the connection into a ThreadLocal
:
public class ConnectionHolder {
private static final ThreadLocal tl = new ThreadLocal<Connection>();
public static void setConnection(Connection c) { tl.set(c); }
public static Connection getConnection() { return tl.get(); }
}
And then your DAO can retrieve it. Now, the preferred way to do all this is to let Spring manage it all. Make your DAOs Spring Beans, inject them into your service layer and in turn inject your service class into your controller. Here's an example of using Spring's preferred JDBC DAO pattern: The Spring Jdbc Template for Database Access - Tutorial
Upvotes: 2