简体   繁体   中英

How to aggregate strings with JPA?

Base Data:

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

Desired Output:

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

I have tried this jpql query:

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

However an exception is raised:

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: new near line 1, column 15

JPA 2.1
Hibernate 4.3.1

See also: https://stackoverflow.com/a/24570617/363573

Firstly to use jpa , you should entity class.

@Entity
class Employee {
   int deptNo;
   String name;

}

Query is

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

You're trying to implement UI-related functionality (how data should be displayed) in the persistence layer, using a JPQL query. That's a bad idea. Retrieve the data in the UI layer using the persistence layer, and then format the data as you wish. For example:

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

And in your 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)));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM