I am developing web application with Java EE 6. In order to minimize calls to database will it be a good idea to have classes:
Data access class (DAO) will call only basic methods getAllClients, getAllProducts, getAllOrders, delete, update
methods - CRUD methods.
Service class which will call CRUD methods but in addition filter methods e.g. findClientByName, findProuctByType, findProductByYear, findOrderFullyPaid/NotPaid
etc... which will be based on basic DAO methods.
Thank you
In my experience (albeit, limited) DAO
classes tend to have all the possible database operations which the application is allowed to perform. So in your case, it will have methods such as getAllClients()
and getClientByName(String name)
, etc.
Getting all the users in your DAO and iterating all over them until you find the one you need will result in unneeded waste of computational time and memory consumption.
If you want to reduce the amount of times that your database is hit you could, maybe, implement some caching mechanism. An ORM framework such as Hibernate should be able to provide what you need as shown here.
EDIT:
As per your comment question, no, your service will not be made redundant. What one does is to usually use a Service
layer to expose the DAO
functionalities. This will, basically, not make the DAO
visible from the from front end of your application. It usually also allows for extra methods, such as, for instance, public String getUserFormatted(String userName)
. This will make use of the getUserByName
function offered by the DAO
but provide some extra functionality.
The Service
layer will also make itself useful should there be a change in specification and you now also need a web service to interface with your application. Having a service layer in between will allow the web service to query the DAO
through the Service
layer.
So basically, the DAO
layer will still worry about the database stuff (CRUD Operations) while the service will adapt the data returned by the DAO
without exposing the DAO.