本文介绍了像GenericDao/JpaRepository一样,如何在服务中保存简单的CRUD代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的网络项目使用spring3,Jpa(休眠).

Our web project uses spring3, Jpa (hibernate).

为了保存CRUD和其他常用方法,我们将存储库设为spring JpaRepository的子类.

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

有时候我只是将存储库注入Controller,对于那些简单(或没有)业务逻辑只读数据访问来说,它很方便.例如列出视图中所有实体类型的对象...我知道所有这些都应该在具有事务范围的服务层中完成,但这确实很方便.

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.

现在有了一条规则:控制器层必须通过服务访问数据层.不允许将存储库注入Controller.

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

例如:

我有一个实体:Country.java

我有interface CountryRepository extends JpaRepository<Country, Long>

我也有CountryService和CountryServiceImpl,其中注入了countryRepository.然后,我必须创建findAll,findOne,count,findAll(带有排序)....方法,这些实现只不过是return countryRepository.findAll() countryRepository.findOne(id) countryRepository.count()...

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?

推荐答案

仅公开应用程序真正使用的服务.我怀疑您是否需要为每个实体使用findAllcount.

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.

这篇关于像GenericDao/JpaRepository一样,如何在服务中保存简单的CRUD代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 23:57