我正在使用spring-data-jpa的CrudRepository
来定义实体的接口,然后使用所有标准的crud方法,而不必明确提供实现,例如:
public interface UserRepo extends CrudRepository<User, Long> {
}
虽然现在我想在我的自定义实现中仅覆盖save()
方法。我怎么能实现这个目标?因为,如果我实现接口UserRepo
,我必须实现从接口CrudRepository
继承的所有其他CRUD方法。
我不能编写自己的具有所有CRUD方法的实现,但只能覆盖一个而不必自己实现所有其他方法吗?
答案 0 :(得分:14)
你可以做一些非常相似的事情,我相信这会实现你正在寻找的结果。
必要步骤:
1)UserRepo
现在将扩展2个接口:
public interface UserRepo extends CrudRepository<User, Long>, UserCustomMethods{
}
2)创建一个名为UserCustomMethods
的新界面(您可以选择名称并在此处和步骤1中进行更改)
public interface UserCustomMethods{
public void mySave(User... users);
}
3)创建一个名为UserRepoImpl
的新类(此处名称执行重要,它应该是RepositoryName Impl ,因为如果你将其称为其他内容,您需要相应地调整Java / XML配置)。此类应仅实现您已创建的 CUSTOM 界面。
提示:您可以在此课程中为您的查询注入实体管理员
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和自定义方法:)