首页 > 解决方案 > 使用 Spring data JPA 获取单列,无需查询

问题描述

我只是想避免根据方法名称约定编写查询和获取数据。下面是我的实体

@Entity
class Product{
     @Id
     private Integer productId;
     private String productName;
     private String productStrategy;
}

我有以下存储库:

interface ProductRepository extends JPARepository<Product,Integer>{
        public Product findByProductStrategy(String productStrategy);
}

以上方法和存储库对我来说工作正常。但我只使用productName上述结果。那么有什么方法可以让我只获取productName而不是获取孔记录。

注意:我知道,我们可以@Query通过编写 HQL 查询或原生查询来实现。但我想在不编写查询的情况下做到这一点,只需使用方法名称约定即可。

标签: javajpaspring-data-jpa

解决方案


考虑使用spring 数据中的Projections

使用您想要的字段为您的实体创建一个投影界面。在你的情况下,它应该看起来像

public interface ProductName {
  String getProductName();
}

然后将您的存储库更改为具有投影接口本身的返回类型。春天会照顾其余的。

public interface ProductRepository extends JPARepository<Product,Integer>{
        public ProductName findByProductStrategy(String productStrategy);
}

推荐阅读