java - 如何将休眠查询的结果映射到 DTO 对象?
问题描述
我的项目中有以下 3 个Hibernate
实体Java
:
公司状态
@Entity(name = "company_status")
@Table(name = "company_status")
public class CompanyStatus implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@JsonProperty
@Column(name = "company_status_id")
private Integer companyStatusId;
@JsonProperty
@Column(name = "company_status_label")
private String companyStatusLabel;
}
员工状态
@Entity(name = "employee_status")
@Table(name = "employee_status")
public class EmployeeStatus implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonProperty
@Column(name = "employee_status_id")
private Integer employeeStatusId;
@JsonProperty
@Column(name = "employee_status_name")
private String employeeStatusName;
// many other fields
}
CompanyStatusEmployeeStatus(链接 2 个实体的实体 - 一对一关系)
@Entity(name = "company_status_employee_status")
@Table(name = "company_status_employee_status")
public class CompanyStatusEmployeeStatus implements Serializable {
// int(20)
@Id
@JsonProperty
@Column(name = "company_status_id")
private Integer companyStatusId;
// int(20)
@JsonProperty
@Column(name = "employee_status_id")
private Integer employeeStatusId;
}
我只想将我的 JSON 响应中的必要字段返回到前端,所以为了做到这一点,我创建了一个较小的CompanyStatusDTO
对象,该对象也EmployeeStatusDTO
嵌套了一个列表
公司状态DTO
public class CompanyStatusDTO {
@JsonProperty
private Integer companyStatusId;
@JsonProperty
private String companyStatusLabel;
@JsonProperty
private List <EmployeeStatusDTO> employeeStatusDTOs;
}
员工状态DTO
public class EmployeeStatusDTO {
@JsonProperty
private Integer employeeStatusId;
@JsonProperty
private String employeeStatusName;
}
但是,我对使用 Hibernate 比较陌生 - 有没有一种方法可以创建一个查询,将结果直接从我的MySQL
数据库映射到我的CompanyStatusDTO
对象?
如果是这样,我该怎么做?
解决方案
您可以使用 NativeQuery 将查询结果直接映射到所需的 DTO(数据类型必须匹配)
String q = "select ... from table"; // your sql query
Query query = getEntityManager().createNativeQuery(q, "EmployeeStatusDTO");
EmployeeStatusDTO data = (EmployeeStatusDTO) query.getSingleResult();
return data;
推荐阅读
- database - 奇怪的 mikrotik dns 与 firebird 数据库的关系
- php - 使用 Cookie 或 Session 哪个?laravel 5.7 - 存储数据 5 分钟
- sql-server - 在sql server中值等于或空时对行进行分组
- varnish - Varnish:使每个 API 密钥对象分别缓存
- java - 如何在使用条件查询进行左连接时在第二个表参数上添加过滤器
- qt - QAbstractTableModel::columnCount 和/或 QAbstractTableModel::rowCount 中的参数“QModelIndex &parent”何时有用?
- r - 在 Amazon EC2 Linux 实例上安装 SPDEP、SPLM 和其他软件包
- mercurial - 找出用户的电子邮件?
- java - 由于注入持久性依赖项失败,无法在 Spring Boot 应用程序上运行测试
- python - python中的FFT频谱图