如何在Spring中只实现CrudRepository的具体方法?

我正在使用spring-data-jpa的CrudRepository来定义一个实体的接口,然后使用所有标准的crud方法而不必显式提供一个实现,例如:

 public interface UserRepo extends CrudRepository { } 

虽然现在我想在我的自定义实现中只覆盖save()方法。 我怎么能实现这个目标? 因为,如果我实现了UserRepo接口,我必须实现从接口CrudRepositoryinheritance的所有其他CRUD方法。

我不能编写自己的实现,它具有所有CRUD方法,但只重写一个而不必自己实现所有其他方法吗?

你可以做一些非常相似的事情,我相信这会达到你想要的结果。

步骤必要:

1) UserRepo现在将扩展2个接口:

 public interface UserRepo extends CrudRepository, UserCustomMethods{ } 

2)创建一个名为UserCustomMethods的新界面(您可以选择名称并在此处和步骤1中更改)

 public interface UserCustomMethods{ public void mySave(User... users); } 

3)创建一个名为UserRepoImpl的新类(此处名称很重要,它应该是RepositoryName Impl ,因为如果你将其称为其他内容,则需要相应地调整Java / XML配置)。 这个类应该只实现你创建的CUSTOM接口。

提示:您可以在此类中为您的查询注入entitymanager

 public class UserRepoImpl implements UserCustomMethods{ //This is my tip, but not a must... @PersistenceContext private EntityManager em; public void mySave(User... users){ //do what you need here } } 

4)在任何需要的地方注入UserRepo ,享受CRUD和自定义方法:)