Skip to content
Advertisement

DAO design pattern: where should the database access be implemented?

I am building a Java application that uses a database and I’m using a DAO design pattern: in my code, all objects classes have an associated DAO class that implements an interface with get, save and update methods. For instance, for a User object, I will have the following class (ConnectionDB implements the connection to the database):

JavaScript

Here is the Dao interface for reference:

JavaScript

This way works pretty fine but as I have more and more classes in my application, and a DAO class for each one of them, I have a lot of repetitive code. For instance, the only difference between the get implementation on different objects is the name and type of the primary key and the call to the constructor.

In order to make the code more generic, I tried to implement a fetchItem method in the ConnectionDB class that would be able to query an item from the database:

JavaScript

With this implementation, I can now replace my first get method in the UserDAO class by the following simplified code:

JavaScript

While this new implementation is simpler and allows the get methods to only do what they’re supposed to do (here, create a User object with the right parameters from the DB), I find it a bit dangerous as I’ll have to make a lot of casts; as I have a lot of Object variables in my code I’m not sure whether it’ll be easy to debug the code if something fails in any of these function calls.

So here’s my question: which implementation is better, easier to maintain and safer?

Advertisement

Answer

Connection DB is a very bad place to define such implementation. It is just a link with a specific database thats all. You violate single responsibility rule. Better to implement base generic class for all DAO’s and place common logic there.
Also if you will use Hibernate framework, you will not need to work with query strings and Object variables casts.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement