【问题标题】:How to override findById with projection in Spring Data如何在 Spring Data 中使用投影覆盖 findById
【发布时间】:2020-10-21 23:09:01
【问题描述】:

在我的存储库中,我需要将 Projection 用于 findById 方法:

@Repository
public interface ForumRepository extends CrudRepository<Forum,Integer> {
        ForumDTO findById(Integer id);
}

但是由于 CrudRepository 中已经存在 findByID,所以我不能用不同的返回类型覆盖它,还有其他方法可以归档它吗?

【问题讨论】:

    标签: spring spring-data spring-data-jpa


    【解决方案1】:

    我刚刚发现我不需要覆盖它,因为我可以使用 getBy 而不是 findBy

    public interface ForumRepository extends CrudRepository<Forum,Integer> {
            ForumDTO getById(Integer id);
    }
    

    【讨论】:

    • 由于 SpringFramwork JPA 2.5 版,getById() 是 JpaRepository 中的内置方法
    【解决方案2】:

    或者,您可以将方法泛化并传入 dto 类。

    <T> T findById(Integer id, Class<T> type);
    

    这也适用于 Optional。

    <T> Optional<T> findById(String id, Class<T> type);
    

    为了使用它,你必须传入你想要返回的类型。

    ForumDTO forum = forumRepo.findById(378583, ForumDTO.class);
    

    来源:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projection.dynamic

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 2016-03-30
      • 2018-03-05
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 2020-02-02
      相关资源
      最近更新 更多