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

时间:2020-08-19 15:06:27

标签: java mysql json hibernate dto

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

CompanyStatus

@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列表

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对象的查询?

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

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

我创建了该库,以允许在JPA模型与自定义接口或抽象类定义的模型之间轻松进行映射,例如类固醇上的Spring Data Projections。这个想法是,您可以按自己喜欢的方式定义目标结构(域模型),并通过JPQL表达式将属性(获取器)映射到实体模型。

如果您稍微调整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 Data集成使您可以像使用Spring Data Projections一样使用它:https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

答案 2 :(得分:0)

您可以尝试以下方法:

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