0

In a canonical Spring MVC implementation, the architecture goes something like this

+--controller
| |
| +--MyController (@Controller, calling MyService)
|
+--service
| |
| +--MyService (interface)
| +--MyServiceImpl (@Service, calls MyDAO)
|
+--dao
| |
| +--MyDAO (interface)
| +--MyDAOImpl (@Repository, MyEntity CRUD)
|
+--entity
  |
  +--MyEntity (@Entity, corresponding to my_table in DB)

My question is simple: What does the use of the @Service contribute to the call hierarchy? Most service classes I've seen simply encapsulate methods from the DAO.

E.g.:

@Transactional
public List<Entity> getEntities() {
    return entityDAO.getEntities();
}

@Transactional
public void saveEntity(Entity val) {
    entityDAO.saveEntity(val);
}

Why not just bypass it and call the DAO directly from the @Controller?

RELATED: Is it bad practice that a controller calls a repository instead of a service? (formulated more abstractly outside any framework)

amphibient
  • 29,770
  • 54
  • 146
  • 240

1 Answers1

1

While it's true that most service classes essentially call the DAO classes, you would want to create this structure because the service layer is where you would have your business logic.

Say you would want to do some validation on user input, have a different database query based on the passed parameters or handle database errors by converting them to appropriate business exceptions. These are things you would typically want to have in the service layer.

Daniel Jacob
  • 1,455
  • 9
  • 17
  • sounds reasonable. it could be that my experience with stupid-simple services simply encapsulating DAO and nothing else is only due to my lack of exposure to more sophisticated examples – amphibient Feb 06 '22 at 19:57
  • and aside from those things mentioned it is a good practice to keep your database objects and domain models seperate. – Daniel Jacob Feb 06 '22 at 20:29