首页 > 解决方案 > 使用列表字段休眠自定义 DTO

问题描述

我有 2 个实体

@Entity
public class DeptEmployee {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long id;

    private String employeeNumber;

    private String designation;

    private String name;

    @ManyToOne
    private Department department;

    // constructor, getters and setters 
}
@Entity
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long id;

    private String name;

    @OneToMany(mappedBy="department")
    private List<DeptEmployee> employees;

    public Department(String name) {
        this.name = name;
    }

    // getters and setters 
}

我知道我可以Result像这样提取 DTO:

public class Result {
    private String employeeName;

    private String departmentName;

    public Result(String employeeName, String departmentName) {
        this.employeeName = employeeName;
        this.departmentName = departmentName;
    }

    public Result() {
    }

    // getters and setters 
}
Query<Result> query = session.createQuery("select new com.baeldung.hibernate.pojo.Result(m.name, m.department.name)"
  + " from com.baeldung.hibernate.entities.DeptEmployee m");
List<Result> results = query.list();

(感谢本文中的示例:https ://www.baeldung.com/hibernate-query-to-custom-class )



现在我想提取一个包含部门名称和该部门员工姓名列表的 DTO。

public class Result2 {
    private String departmentName;

    private List<String> employeeNames;

    // Constructor ???

    public Result2() {
    }

    // getters and setters 
}

我的问题是:

标签: javahibernatehql

解决方案


我认为您无法在 HQL 中实现它。你可以使用你已经拥有的东西。重新映射List<Result>List<Result2>. 首先分组,departmentName然后您可以创建Result2对象。sql查询和传输的数据将是相同的。

List<Result2> results= query.list().stream()
  .collect(groupingBy(Result::getDepartmentName))
  .entrySet().stream()
  .map(e -> new Result2(
    e.getKey(),
    e.getValue().stream().map(Result::getEmployeeName).collect(Collectors.toList())))
  .collect(Collectors.toList());

推荐阅读