![](/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.