java 在 Spring 中实现 CrudRepository。我应该遵循的最佳设计是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29467886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:20:08  来源:igfitidea点击:

Implementing CrudRepository in Spring. What's the best design I should follow?

javaspringdesign-patternsspring-data

提问by Faraj Farook

I have the User Repository extend from the CrudRepository as below

我有用户存储库从 CrudRepository 扩展如下

public interface UserRepository extends CrudRepository<User, Long>, DatatablesCriteriasRepository<User> 

DatatablesCriteriasRepositoryhas a function which need to be implmented separately for different repositories.

DatatablesCriteriasRepository有一个功能需要为不同的存储库单独实现。

So I created the repository implementation class like this. In the implpackage.

所以我创建了这样的存储库实现类。在impl包里。

public class UserRepositoryImpl implements DatatablesCriteriasRepository<User> 

Please note this is to implement the functions in DatatablesCriteriasRepositoryonly. I dont want to override the default functionalities presented in CrudRepositoryby the framework.

请注意,这只是为了实现功能DatatablesCriteriasRepository。我不想覆盖CrudRepository框架提供的默认功能。

But If I do something like this, it will suit more in the code design, as UserRepositoryImplactually implements UserRepositoryas the name suggests.

但是如果我做这样的事情,它会更适合代码设计,正如名字所暗示的那样UserRepositoryImpl实际实现UserRepository

public class UserRepositoryImpl implements UserRepository 

But again this will force me to extend all the functions in the UserRepository interface. How can I solve this issue by the way in a good code design?

但这将再次迫使我扩展 UserRepository 接口中的所有功能。如何在好的代码设计中顺便解决这个问题?

Can the UserRepositoryImplhas this name while it implements DatatablesCriteriasRepository?

可以在UserRepositoryImpl实现时使用这个名称DatatablesCriteriasRepository吗?

回答by Faraj Farook

Spring's repositories custom implementationsdocumentation provides the way to implement this as @JBNizet pointed it to me.

Spring 的存储库自定义实现文档提供了实现这一点的方法,正如@JBNizet 向我指出的那样。

Extract from the documentation is as follows.

文档摘录如下。

Interface for custom repository functionality

自定义存储库功能的接口

interface UserRepositoryCustom {
  public void someCustomMethod(User user);
}

Implementation of custom repository functionality

自定义存储库功能的实现

class UserRepositoryImpl implements UserRepositoryCustom {

  public void someCustomMethod(User user) {
    // Your custom implementation
  }
}

Changes to the your basic repository interface

对基本存储库界面的更改

interface UserRepository extends CrudRepository<User, Long>, UserRepositoryCustom {

  // Declare query methods here
}