java - 使用列表字段休眠自定义 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
}
我的问题是:
- 那可能吗?
- 什么是构造函数
Result2
? - 提取这个的 hql 查询是什么
Result2
?
解决方案
我认为您无法在 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());
推荐阅读
- caching - 在这些缓存场景中,代码在哪里执行?
- cordova - 如何在没有 Ionic 服务的情况下在我的设备上测试我的应用程序
- docker - 无法在主节点上运行 Kubernetes 仪表板
- java - 在 oracle DB 中插入字符串值在 sql developer 中显示空值
- javascript - 在 JavaScript 中为数组的多个元素分配相同的值
- c++ - 在 SFML 中使用 TcpSocket 发送数据会导致分段错误
- c# - 如果我将 Mutex 声明为静态 (WPF),我是否需要担心它会被垃圾回收?
- inheritance - 如何在java中的Builder模式中继承
- android - 通过 android studio 代码获取我的本地 IP 地址
- javascript - 使用 jQuery 在第一行之后包装括号文本