【发布时间】:2020-05-20 16:52:59
【问题描述】:
我正在为我的项目使用 Spring Boot + JPA。我想要我表中每个 type 的 fieldName 列表。所以我通过使用JPQL 使用带有命名参数的查询 来做到这一点。我在存储库中做了两种方法。
-
第一种方法:
此方法用于获取type的不同列表。
@Query(value = "SELECT DISTINCT fc.type FROM FieldCapabilityModel fc")
List<String> findDistinctType();
-
第二种方法:
此方法用于获取特定type的名称列表。
@Query("SELECT fc.fieldName FROM FieldCapabilityModel fc where fc.type=:type")
List<String> findByType(@Param("type) String type);
这是我的service 组件。
@Service
public class FieldCapabilityService {
@Autowired
FieldCapabilityRepo fcRepo;
public List<Map<String, Object>> getAllFieldAndType() {
// First Method is called here
return fcRepo.findDistinctType().stream().map(type -> {
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("type", type);
// Second Method is called here
resultMap.put("field", fcRepo.findByType(type));
return resultMap;
}).collect(Collectors.toList());
}
}
当我使用休息控制器调用时,我的 API 响应是:
{
"code": 200,
"message": "Data Fetched",
"data": [
{
"field": [
"name.lname",
"city",
"name.fname",
"name",
"id"
],
"type": "text"
},
{
"field": [
"_ignored"
],
"type": "_ignored"
},
{
"field": [
"_seq_no"
],
"type": "_seq_no"
}
]
}
我得到了我想要的准确输出,而且这是一个简单的数据响应,我有超过 16 种类型。尽管我想知道这是一种有效且稳健的方式。
我的问题是:
我们可以为此使用任何其他查询吗?
如果可以,我们可以使用@NamedQuery代替这个,那为什么?
什么应该是这种执行的精简、健壮和高效的方法吗?
如果我想改进此解决方案的任何内容,请给我建议,或者提出比此解决方案更好的新解决方案。
【问题讨论】:
标签: java spring-boot jpa spring-data-jpa