如何使用JPA聚合字符串?

yc0p9oo0  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(114)

基础数据:

DEPTNO ENAME
------ ------
    20 SMITH
    30 ALLEN
    30 WARD
    20 JONES
    30 MARTIN
    30 BLAKE
    10 CLARK
    20 SCOTT
    10 KING
    30 TURNER
    20 ADAMS
    30 JAMES
    20 FORD
    10 MILLER

字符串
期望输出:

DEPTNO EMPLOYEES
------ ---------
    10 CLARK,KING,MILLER
    20 SMITH,FORD,ADAMS,SCOTT,JONES
    30 ALLEN,BLAKE,MARTIN,TURNER,JAMES,WARD


我试过这个jpql查询:

SELECT deptno, new list(ename) as employees
 FROM dept_emp


但有一个例外:
org.hibernate.hql.internal.ast.QuerySyntaxException:意外的token:new靠近第1行,第15列
JPA 2.1

Hibernate 4.3.1
参见:https://stackoverflow.com/a/24570617/363573

kt06eoxx

kt06eoxx1#

首先要使用jpa,你应该实体类。

@Entity
class Employee {
   int deptNo;
   String name;

}

字符串
查询

SELECT e.deptNo , new list(e.name) FROM Employee e GROUP BY e.deptNo

km0tfn4u

km0tfn4u2#

您试图使用JPQL查询在持久层中实现与UI相关的功能(数据应该如何显示)。这是一个坏主意。使用持久层在UI层中重新定义数据,然后根据需要格式化数据。例如:

List<Employee> employees = em.createQuery("select e from Employee e").getResultList();

字符串
在你的presentation layer中:

Multimap<String, Employee> employeesByDepartment = 
    Multimaps.index(employees, Employee::getDepartmentNumber);
for (String departmentNumber : employeesByDepartment.keySet()) {
    System.out.print(departmentNumber);
    System.out.print("\t");
    System.out.println(Joiner.on(", ").join(employeesByDepartment.get(departmentNumber)));
}

tzcvj98z

tzcvj98z3#

这对我很有效。

SELECT deptno,  STRING_AGG(ename, ', ') as employees
FROM dept_emp
GROUP BY deptno

字符串
Refer to this

相关问题