我有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
}
我的问题是:
那可能吗?
Result2
中的构造函数是什么?提取此
Result2
的hql查询是什么? 最佳答案
我认为您无法在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());
关于java - 带有列表字段的 hibernate 自定义DTO,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60038216/