[英]JPQL count multiple many-to-one and group counts by child column
我想構建一個 JPQL 查詢來將該結構的數據映射到這個 DTO:
@AllArgsConstructor
class UserDTO {
long userId;
long countOfContacts;
Map<String,Long> countOfActions; // by type
}
我不知道如何在 JPQL 中提取每個動作類型的計數,這就是我被卡住的地方(看到我的名字?:)):
public interface UserRepository extends CrudRepository<User, Long> {
@Query("SELECT new example.UserDTO( "
+ " u.id, "
+ " COUNT(contacts), "
--> + " ???group by actions.type to map<type,count>??? " <---
+ " ) "
+ " FROM User u "
+ " LEFT JOIN u.actions actions "
+ " LEFT JOIN u.contacts contacts "
+ " GROUP BY u.id")
List<UserDTO> getAll();
}
我使用 postgres 並且如果這在 JPQL 中是不可能的,那么也可以使用本機查詢。
其實我可以用原生查詢解決,用Java映射actions數據,但是感覺不好:
SELECT
u.id,
COALESCE(MIN(countOfContacts.count), 0) as countOfContacts,
ARRAY_TO_STRING(ARRAY_REMOVE(ARRAY_AGG(actions.type || ':' || actions.count), null),',') AS countOfActions
FROM user u
LEFT JOIN (
SELECT
user_id, COUNT(*) as count
FROM contact
GROUP BY user_id
) countOfContacts
ON countOfContacts.user_id = u.id
LEFT JOIN (
SELECT
user_id, type, COUNT(*)
FROM action
GROUP BY user_id, type
) actions
ON actions.user_id = u.id
GROUP BY u.id
;
導致這樣的結果數據:
id | countOfContacts | countOfActions
--------+-----------------+-------------------------
11728 | 0 | {RESTART:2}
9550 | 0 | {}
9520 | 0 | {CLEAR:1}
12513 | 0 | {RESTART:2}
10238 | 3 | {CLEAR:2,RESTART:5}
16531 | 0 | {CLEAR:1,RESTART:7}
9542 | 0 | {}
...
由於在本機查詢中我們無法映射到 POJO,因此我返回List<String[]>
並自己將所有列轉換為UserDTO
的構造函數:
@Query(/*...*/)
/** use getAllAsDTO for a typed result set */
List<String[]> getAll();
default List<UserDTO> getAllAsDTO() {
List<String[]> result = getAll();
List<UserDTO> transformed = new ArrayList<>(result.size());
for (String[] row : result) {
long userId = Long.parseLong(row[0]);
long countOfContacts = Long.parseLong(row[1]);
String countOfActions = row[2];
transformed.add(
new UserDTO(userId, countOfContacts, countOfActions)
);
}
return transformed;
}
然后我將countOfActions
映射到 DTO 的構造函數中的 Java Map<String, Long>
:
class UserDTO {
long userId;
long countOfContacts;
Map<String,Long> countOfActions; // by type
/**
* @param user
* @param countOfContacts
* @param countOfActions {A:1,B:4,C:2,..} will not include keys for 0
*/
public UserDTO(long userId, long countOfContacts, String countOfActionsStr) {
this.userId = userId;
this.countOfContacts = countOfContacts;
this.countOfActions = new HashMap<>();
// remove curly braces
String s = countOfActionsStr.replaceAll("^\\{|\\}$", "");
if (s.length() > 0) { // exclude empty "arrays"
for (String item : s.split(",")) {
String[] tmp = item.split(":");
String action = tmp[0];
long count = Long.parseLong(tmp[1]);
countOfActions.put(action, count);
}
}
}
}
我可以在 DB 層解決它嗎?
不幸的是, JPQL沒有像string_agg或group_concat這樣的聚合函數。 所以你應該自己轉換查詢結果。 首先,您應該像這樣創建一個“普通”查詢,例如:
@Query("select new example.UserPlainDto( " +
" a.user.id, " +
" count(distinct c.id), " +
" a.type, " +
" count(distinct a.id) " +
") " +
"from " +
" Action a " +
" join Contact c on c.user.id = a.user.id " +
"group by " +
" a.user.id, a.type")
List<UserPlainDto> getUserPlainDtos();
(它是HQL - JPQL 的 Hibernate 擴展)
此查詢的結果將是一個普通表,例如:
|--------|---------------|-------------|-------------|
|user_id |countact_count |action_type |action_count |
|--------|---------------|-------------|-------------|
|1 |3 |ONE |1 |
|1 |3 |TWO |2 |
|1 |3 |THREE |3 |
|2 |2 |ONE |1 |
|2 |2 |TWO |2 |
|3 |1 |ONE |1 |
|--------|---------------|-------------|-------------|
然后,您應該將該結果分組到UserDto
集合中,如下所示:
default Collection<UserDto> getReport() {
Map<Long, UserDto> result = new HashMap<>();
getUserPlainDtos().forEach(dto -> {
long userId = dto.getUserId();
long actionCount = dto.getActionCount();
UserDto userDto = result.getOrDefault(userId, new UserDto());
userDto.setUserId(userId);
userDto.setContactCount(dto.getContactCount());
userDto.getActions().compute(dto.getActionType(), (type, count) -> count != null ? count + actionCount : actionCount);
result.put(userId, userDto);
});
return result.values();
}
然后瞧,您將在Collection<UserDto>
得到這樣的結果:
[
{
"userId": 1,
"contactCount": 3,
"actions": {
"ONE": 1,
"TWO": 2,
"THREE": 3
}
},
{
"userId": 2,
"contactCount": 2,
"actions": {
"ONE": 1,
"TWO": 2
}
},
{
"userId": 3,
"contactCount": 1,
"actions": {
"ONE": 1
}
}
]
上面使用了 DTO:
@Value
class UserPlainDto {
long userId;
long contactCount;
ActionType actionType;
long actionCount;
}
@Data
class UserDto {
long userId;
long contactCount;
Map<ActionType, Long> actions = new HashMap<>();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.