首页 > 解决方案 > 如何将休眠查询的结果映射到 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对象?

如果是这样,我该怎么做?

标签: javamysqljsonhibernatedto

解决方案


您可以使用 NativeQuery 将查询结果直接映射到所需的 DTO(数据类型必须匹配)

String q = "select ... from table"; // your sql query
Query query = getEntityManager().createNativeQuery(q, "EmployeeStatusDTO");
EmployeeStatusDTO data = (EmployeeStatusDTO) query.getSingleResult();
return data;

推荐阅读