In class we\'re now learning how to build up a Spring application, even though spring isn\'t directly involved, we learned how to make the interfaces for DAO and service lay
Generally a Spring service is transactional. Things go into a particular service method because they ought to be grouped together in the same transaction. If you want to retrieve an object from the database, twiddle it, and save the new version, the retrieval and save ought to be in the same service method. So your service methods are determined according to what you need the application to do for the user.
I try to restrict controllers to doing work related to validating http parameters, deciding what service method to call with what parameters, what to put in the httpsession or request, what view to redirect or forward to, or similar web-related stuff.
As far as validation goes: Validating input parameters in the controller is a good thing to make sure nobody can break your application with bogus inputs. Validation in the controller tends to be about making sure the inputs are syntactically ok (including detecting injection attacks) while service-level validation is about making sure the state of things in the database is what you expect it to be.
So controllers contain web-framework infrastructure code, services contain application logic code.
If you wish to have controllers be able to persist changes to a Child
object, then traditionally you would have a method in the service named something like ChildService.update(Child newchild)
, which will handle calling the correct DAOs to persist the new version of this Child.
Controllers are free to ask the service for a Child, change the fields around (conceivably based on some user input) - a sane design would have the Controller doing some work with the Child POJO and then asking the Service to persist the change. The model POJO should know nothing about a controller, service, or DAO but just simply hold data as you suggest - certainly you would not want every call to setName()
or setGender()
to automatically result in a database update.
Instead, the controller and/or service should acquire a Child
object, do whatever work it needs to the object in it's unit of work, and then ask a Service (and then the DAO) to persist the changes.
Validation can take place in several layers - the Controller might want to validate any input from the web user, and the Service may want to validate that it has a valid Child
object before it persists it. It especially makes sense to have some level of validation in both layers in case you want to re-use this Service in other capacities - such as exposing a REST interface, a different front-end, etc.