Java 如何在春季只实施具体的积存方法?

Java 如何在春季只实施具体的积存方法?,java,spring,spring-data-jpa,Java,Spring,Spring Data Jpa,我使用spring data jpa的CRUDepository来定义实体的接口,然后使用所有标准crud方法,而不必显式提供实现,例如: public interface UserRepo extends CrudRepository<User, Long> { } 公共接口UserRepo扩展了crudepository{ } 尽管现在我只想在自定义实现中重写save()方法。我怎样才能做到这一点?因为,如果我实现接口UserRepo,我必须实现从接口crudeposito

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

public interface UserRepo extends CrudRepository<User, Long> {

}
公共接口UserRepo扩展了crudepository{
}
尽管现在我只想在自定义实现中重写
save()
方法。我怎样才能做到这一点?因为,如果我实现接口
UserRepo
,我必须实现从接口
crudepository
继承的所有其他CRUD方法


难道我不能编写自己的实现,其中包含所有CRUD方法,但只覆盖一个,而不必自己实现所有其他方法吗?

你可以做一些非常类似的事情,我相信这将实现你想要的结果。

必要步骤:

  • UserRepo
    现在将扩展2个接口:

    公共接口UserRepo扩展了Crudepository、UserCustomMethods{

    }

  • 创建名为
    UserCustomMethods
    的新接口(您可以在此处和步骤1中选择名称并进行更改)

    公共接口用户自定义方法{ public void mySave(用户…用户)

    }

  • 创建一个名为
    UserRepoImpl
    的新类(这里的名称很重要,它应该是RepositoryNameImpl,因为如果调用其他名称,则需要相应地调整Java/XML配置)。此类应仅实现您创建的自定义接口

  • 提示:您可以在此类中插入entitymanager以用于查询

    public class UserRepoImpl implements UserRepo {
        
        //This is my tip, but not a must...
        @PersistenceContext
        private EntityManager em;
    
        public void mySave(User... users){
            //do what you need here
        }
    }
    
  • 在任何需要的地方注入
    UserRepo
    ,并享受CRUD和自定义方法:)

  • 因此,为了只覆盖save方法,我将在UserCustomMethods/UserRepoImpl?中声明/实现save方法?。您在这里给出的示例显示了一个附加方法,但这是否也适用于现有方法?是的,您可以向自定义接口添加与您要覆盖的默认方法具有相同签名的方法,并在实现自定义接口的Impl类中以您的方式实现它们:以这种方式,Spring数据将使用自定义实现而不是默认实现。至少对于Spring数据JPA 1.7.2中的delete方法,这对我是有效的。我如何在UserRepoImpl:)中使用UserRepo(由Spring数据自动提供)的非自定义方法?这是否可以作为Spring数据rest存储库公开?我是否可以将自定义mySave()标记为响应PUT/user/{id}?