【问题标题】:How to implement only specific method of CrudRepository in Spring?如何在 Spring 中仅实现 CrudRepository 的特定方法?
【发布时间】:2014-05-16 23:37:00
【问题描述】:

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

public interface UserRepo extends CrudRepository<User, Long> {

}

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

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

【问题讨论】:

    标签: java spring spring-data-jpa


    【解决方案1】:

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

    必要步骤:

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

       public interface UserRepo extends CrudRepository<User, Long>, UserCustomMethods{
      
       }
      
    2. 创建一个名为 UserCustomMethods 的新接口(您可以在此处和步骤 1 中选择名称并进行更改)

       public interface UserCustomMethods{
           public void mySave(User... users);
      
       }
      
    3. 创建一个名为 UserRepoImpl 的新类(这里的名称确实很重要,它应该是 RepositoryNameImpl,因为如果你叫它别的名字,你需要相应地调整 Java/XML 配置)。此类应仅实现您创建的 CUSTOM 接口。

    提示:您可以在此类中注入 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
        }
    }
    
    1. 在任何需要的地方注入 UserRepo,并享受 CRUD 和您的自定义方法 :)

    【讨论】:

    • 因此,为了仅覆盖保存方法,我将在 UserCustomMethods/UserRepoImpl? 中声明/实现保存方法。您在此处给出的示例显示了一种附加方法,但这是否也适用于现有方法?
    • 是的,您可以将具有相同签名的方法添加到您的自定义接口中,这些方法与您想要覆盖的默认方法的签名相同,并在实现自定义接口的 Impl 类中以您的方式实现它们:这样,Spring Data将使用您的自定义实现而不是默认实现。至少这对我来说适用于 Spring Data JPA 1.7.2 中的删除方法。
    • 如何在 UserRepoImpl 中使用 UserRepo 的非自定义方法(由 spring 数据自动提供) :)?
    • 这是否可以作为 spring-data-rest 存储库公开?
    • 我可以将自定义 mySave() 标记为响应 PUT /user/{id} 吗?
    猜你喜欢
    • 2017-06-07
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多