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

mem*_*und 14 java spring spring-data-jpa

我使用CrudRepositoryspring-data-jpa来定义一个实体的接口,然后使用所有标准的crud方法,而不必明确地提供一个实现,例如:

public interface UserRepo extends CrudRepository<User, Long> {

}
Run Code Online (Sandbox Code Playgroud)

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

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

Sha*_*yam 16

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

步骤必要:

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

public interface UserRepo extends CrudRepository<User, Long>, UserCustomMethods{

}
Run Code Online (Sandbox Code Playgroud)

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

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

}
Run Code Online (Sandbox Code Playgroud)

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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