I just started work on Spring Boot
, using Spring Data JPA
. When I generate model from table, I create a modelRepo which extends JpaRepository<myModel, String>
public interface userRepository extends JpaRepository<User, String>{
}
Then from a controller, I can easy call userRepository.findAll()
to get data.
However, when I look on some tutorials, they have extra several steps before calling findAll(). Take a look below:
public interface userService{
Iterator findAll();
}
public class userServiceImpl implements userService{
@Autowired
UserRepository userRepository
@Override
Iterator findAll(){
return userRepository.findAll();
}
}
Somethings like that, I can query the data directly from userRepository
as long as @Autowired to inject userRepository
.
In some example, they do same structure at above. Can anyone explain why do we need service
and serviceImpl
before calling data.
Because the so-called "service" classes ("inherited" with the N-tier architecture) are where the business logic "lives". In the end, it depends on your approach/design guidelines, the way you would like to manage transactions, structure your project, etcetera.
If you only need to make a call to the database and return that data, you can safely skip the "service" call/class. On the other hand, if you are doing something "in the real life", you will end up using those "service" classes a lot since most of the operations (read: business logic) is going to be there, so you would want to have all that behavior isolated in one place — otherwise you would be injecting beans everywhere without following any "project organization" among other things. It's a little bit tedious sometimes, but on the other hand, you know where to look for whenever you need to change something. In medium to large projects this is quite important; even more if you have several people modifying the same code base.
TIP: Keep your classes small. Injecting tons of beans (repositories, services and what not) on a "service" class is bad design and may lead you to other non-senses.