Java – spring data JPA repo, why do you need interface services and service implementations

I've just started developing spring boot. JPA using spring data JPA When I generate a model from a table, I create a modelrepo that extends the jparepository < mymodel, string >

public interface userRepository extends JpaRepository<User,String>{
}

Then from the controller, I can easily call userrepository Findall() to get the data

However, when I look at some tutorials, they have a few steps before calling findall() Look at the following:

public interface userService{
Iterator findAll();

}

public class userServiceImpl implements userService{
       @Autowired
       UserRepository userRepository
       @Override
       Iterator findAll(){
        return userRepository.findAll();
       }
    }

For things like this, I can query data directly from the userrepository, as long as @ Autowired is injected into the userrepository

In some examples, they perform the same structure above Anyone can explain why we need service and serviceimpl before calling data

Solution

Because the so-called "service" class (inheritance and n-tier Architecture) is the place where business logic "lives" Finally, it depends on your methodology / design guidelines, how you want to manage transactions, building projects, and so on

If you only need to call the database and return the data, you can safely skip the "service" call / class On the other hand, if you are doing something "in real life", you will eventually use these "service" classes. Because most operations (reading: business logic) will exist, you will want to isolate all these behaviors in one place - otherwise you will inject beans anywhere without following any "project organization", etc Sometimes it's a little boring, but on the other hand, whenever you need to change something, you know where to look In large and medium-sized projects, this is very important; If you have several people modifying the same code base, even more

Tip: keep the class small Injecting a large number of beans (repositories, services and what is not) into the "service" class is a bad design and may lead to other non - sensory problems

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>