带有列表字段的 Hibernate 自定义 DTO

Hibernate custom DTO with a list field

我有 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 
}

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

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 
}

我的问题是:

我认为您无法在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());