如何将 Hibernate 查询的结果映射到 DTO 对象?

How to map results of a Hibernate Query to a DTO object?

我的 Java 项目中有以下 3 个 Hibernate 实体:

公司状况

@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;
}

我只想 return 我对前端的 JSON 响应中的必要字段,所以为了做到这一点,我创建了一个较小的 CompanyStatusDTO 对象,它也有EmployeeStatusDTO 嵌套列表

CompanyStatusDTO

public class CompanyStatusDTO {

    @JsonProperty
    private Integer companyStatusId;

    @JsonProperty
    private String companyStatusLabel;

    @JsonProperty
    private List <EmployeeStatusDTO> employeeStatusDTOs;

}

EmployeeStatusDTO

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;

你可以试试这个:

public class Dao{

    private SessionFactory sessionFactory;
    
    public Dao(SessionFactory sessionFactory) {
      this.sessionFactory = sessionFactory;
    }

    public <T> T save(final T o){
      return (T) sessionFactory.getCurrentSession().save(o);
    }


    public void delete(final Object object){
      sessionFactory.getCurrentSession().delete(object);
    }

    public <T> T get(final Class<T> type, final Long id){
      return (T) sessionFactory.getCurrentSession().get(type, id);
    }

    public <T> List<T> getAll(final Class<T> type) {
      final Session session = sessionFactory.getCurrentSession();
      final Criteria crit = session.createCriteria(type);
  return crit.list();
    }
// and so on, you should get the idea

然后在服务层就可以这样访问了:

    private Dao dao;
   
    @Transactional(readOnly = true)
    public List<MyEntity> getAll() {
      return dao.getAll(MyEntity.class);
    }

这是 Blaze-Persistence Entity Views 的完美用例。

我创建了库以允许在 JPA 模型和自定义接口或抽象 class 定义的模型之间轻松映射,类似于 Spring 类固醇数据投影。这个想法是您按照自己喜欢的方式定义目标结构(领域模型),并通过 JPQL 表达式将属性(getter)映射到实体模型。

如果稍微调整 CompanyStatusCompanyStatusEmployeeStatus 实体并添加以下内容:

public class CompanyStatus implements Serializable {
  //...
  @OneToMany(mappedBy = "companyStatus")
  private Set<CompanyStatusEmployeeStatus> employeeStatuses;
}

public class CompanyStatusEmployeeStatus implements Serializable {
    //...
    @JsonProperty
    @ManyToOne(fetch = LAZY)
    @JoinColumn(name = "company_status_id", insertable = false, updatable = false)
    private CompanyStatus companyStatus;

    @JsonProperty
    @ManyToOne(fetch = LAZY)
    @JoinColumn(name = "employee_status_id", insertable = false, updatable = false)
    private EmployeeStatus employeeStatus;
}

您的模型可能如下所示:

@EntityView(CompanyStatus.class)
public interface CompanyStatusDTO {
    @IdMapping
    Integer getCompanyStatusId();
    String getCompanyStatusLabel();
    @Mapping("employeeStatuses.employeeStatus")
    List<EmployeeStatusDTO> getEmployeeStatusDTOs();
}
@EntityView(EmployeeStatus.class)
public interface EmployeeStatusDTO {
    @IdMapping
    Integer getEmployeeStatusId();
    String getEmployeeStatusName();
}

查询就是将实体视图应用于查询,最简单的就是通过 id 进行查询。

CompanyStatusDTO c = entityViewManager.find(entityManager, CompanyStatusDTO.class, id);

Spring 数据集成让您几乎可以像 Spring 数据投影一样使用它:https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features