![](/img/trans.png)
[英]How to display User and list of all Books that he rented - SpringBoot, JPA, MySql
[英]Springboot + JPA : List all fieldnames for each fieldtype
我正在为我的项目使用 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());
}
}
当我使用 rest controller 打电话时,我的 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"
}
]
}
我得到了我想要的确切的 output,这也是一个简单的数据响应,我有超过 16 种类型。 尽管我想知道这是一种有效且稳健的方式。
我的问题是:
我们可以为此使用任何其他查询吗?
如果可以,我们可以使用@NamedQuery
代替这个,那为什么?
这种执行的简化、稳健和高效的方法应该是什么?
如果我想改进这个解决方案的任何内容,或者如果它比这个解决方案更好,请给我建议或者提出一个新的解决方案。
您可以在一个查询中获取所有类型和字段名称
@Query(value = "SELECT NEW org.apache.commons.math3.util.Pair(fc.type as type, fc.fieldName as name) FROM FieldCapabilityModel fc")
public List<Pair<Integer, Integer>> findAllTypeWithName();
然后汇总数据。 创建一个类型为 map,其中 Key 是 fieldNames
Map<String, List<String>> fieldNameByType = fcRepo.findAllTypeWithName()
.stream()
.collect(Collectors.groupingBy(Pair::getKey,
Collectors.mapping(Pair::getValue, Collectors.toList())));
然后,您可以使用此 map 准备您的回复。
return fieldNameByType.entrySet().stream().map(e -> {
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("type", e.getKey());
resultMap.put("field", e.getValue());
return resultMap;
}).collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.