how to save simple CRUD codes in a service, just like GenericDao/JpaRepository?

与世无争的帅哥 提交于 2019-12-11 02:48:00

问题


Our web project uses spring3, Jpa (hibernate).

To save CRUD and other commonly used methods, we made our repositories sub-classes of spring JpaRepository.

Sometimes I just injected repositories to Controller, it is convenient for those simple (or none) business logic read-only data access. e.g. list all objects of an entity type in view... I knew that all these should be done in a service layer with transaction scope, but it is really convenient.

Now comes a rule: controller layer must via Service access data layer. Injecting Repositories into Controller is not allowed.

for example:

I have an Entity: Country.java

And I have interface CountryRepository extends JpaRepository<Country, Long>

Also I have CountryService and CountryServiceImpl, which has countryRepository injected. Then I have to create findAll, findOne, count, findAll(with sorting).... methods, and those implementation is nothing more than return countryRepository.findAll() countryRepository.findOne(id) countryRepository.count()...

And for each entity I have to do the same again and again...

Is it possible that in service layer save those methods using a generic way?


回答1:


Only expose services that your application really uses. I doubt you need a findAll or a count for every entity.

The fact that the implementation of these methods is very simple is a good thing: you won't have any difficulty implementing and testing them. If they become more complex, and need several repository method calls and a bit of business logic, you'll be happy to just have to modify the method, and not change all your design.



来源:https://stackoverflow.com/questions/7658899/how-to-save-simple-crud-codes-in-a-service-just-like-genericdao-jparepository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!