如何在Spring中只实现CrudRepository的具体方法? [英] How to implement only specific method of CrudRepository in Spring?
问题描述
我正在使用spring-data-jpa的 CrudRepository
来定义一个实体的接口,然后拥有所有标准的crud方法,而不必明确提供一个实现,例如:
I'm using CrudRepository
of spring-data-jpa to just define an interface of an entity and then having all standard crud methods without having to provide an implementation explicitly, eg:
public interface UserRepo extends CrudRepository<User, Long> {
}
虽然现在我只想覆盖<我的自定义实现中的code> save()方法。我怎么能实现这个目标?因为,如果我实现接口 UserRepo
,我必须实现从接口继承的所有其他CRUD方法CrudRepository
。
Though now I'd like to override only the save()
method in my custom implementation. How could I achieve this? Because, if I implement the interface UserRepo
, I'd have to implement all other CRUD methods that are inherited from interface CrudRepository
.
我不能编写自己的具有所有CRUD方法的实现,但是只重写一个而不必自己实现所有其他方法吗?
Can't I write my own implementation that has all CRUD methods but overriding only one without having to implement all others myself?
推荐答案
你可以做一些非常相似的,我相信这会达到你想要的结果。
You can do something pretty similar, which I believe will achieve the result you're looking for.
步骤必要:
1) UserRepo
现在将扩展2个接口:
1) UserRepo
will now extend 2 interfaces:
public interface UserRepo extends CrudRepository<User, Long>, UserCustomMethods{
}
2)创建一个名为 UserCustomMethods $ c $的新界面c>(您可以在此处和步骤1中选择名称并进行更改)
2) Create a new interface named UserCustomMethods
(you can choose the name and change both here and in step 1)
public interface UserCustomMethods{
public void mySave(User... users);
}
3)创建一个名为 UserRepoImpl
(此处名称确实很重要,它应该是RepositoryName Impl ,因为如果您将其称为其他内容,则需要调整相应的Java / XML配置)。这个类应该只实现你创建的 CUSTOM 接口。
3) create a new class named UserRepoImpl
(here the name does matter and it should be RepositoryNameImpl, because if you call it something else, you will need to adjust the Java/XML configuration accordingly). this class should implement only the CUSTOM interface you've created.
提示:你可以在这个类中为你的查询注入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和自定义方法:)
4) Inject UserRepo
wherever you need, and enjoy both CRUD and your custom methods :)
这篇关于如何在Spring中只实现CrudRepository的具体方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!