java - 使用 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 查询或原生查询来实现。但我想在不编写查询的情况下做到这一点,只需使用方法名称约定即可。
解决方案
考虑使用spring 数据中的Projections
使用您想要的字段为您的实体创建一个投影界面。在你的情况下,它应该看起来像
public interface ProductName {
String getProductName();
}
然后将您的存储库更改为具有投影接口本身的返回类型。春天会照顾其余的。
public interface ProductRepository extends JPARepository<Product,Integer>{
public ProductName findByProductStrategy(String productStrategy);
}
推荐阅读
- mongodb - 官方 mongodb go-driver heroku 连接到 mongodb atlas 沙箱
- javascript - Google Drive API 文件列表问题
- c++ - 错误:在 C++ 中无效使用非静态成员函数
- sql - 为这个项目构建查询以获得可用的席位
- mongodb - 当我尝试打开 mongo shell 时出现此错误
- matlab - MATLAB R2018b 基于变量的半透明散点图
- c++ - 如何将串行数据解析为 int 值
- python - 为什么我不能只分配自我指针?
- python - 如何在 Python 3 中解析这个嵌套的字典数据结构?
- python - 安装requirement.txt时遇到问题