使用带有DTO投影的实体图使用ResultTransformer返回空值

时间:2018-06-12 11:05:21

标签: spring spring-data-jpa criteria-api entitygraph resulttransformer

您好我是jpa +标准API + hibernate的新手..

我怀疑在jpa标准API中使用ResultTransformer。

我有两个实体部门和员工。部门和员工之间的一对多映射。我想使用带有DTO投影的实体图

1。系

@Entity
@NamedEntityGraph(name = "departmentWithEmployee", attributeNodes = @NamedAttributeNode("setOfEmployee"))
@Table(name = "tblDepartment")
public class Department {

    @Id
    private String id;

    private String name;

    @OneToMany(mappedBy = "department")
    private Set<Employee> setOfEmployee;

    //....getter & setter

}

2。雇员

@Entity
@Table(name = "tblEmployee")
public class Employee {

    @Id
    private String id;

    @ManyToOne
    @JsonIgnore
    private Department department;

    private String firstName;

    private String lastName;

    //...getter & setter

}

DepartmentDTO.java

public class DepartmentDTO implements Serializable {

    private String id;

    private String name;

    private Set<EmployeeDTO> setOfEmployee;

    //... getter & setter..
}

I am executing query with entity graph and I want to get all departments from database and serialize with DepartmentDTO.java

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<DepartmentDTO> criteria = builder.createQuery(DepartmentDTO.class);
Root root = criteria.from(Department.class);
criteria.select(root);
EntityGraph graph = entityManager.getEntityGraph("departmentWithEmployee");
List<DepartmentDTO> list = entityManager.createQuery(criteria).setHint("javax.persistence.fetchgraph", graph)
                .unwrap(org.hibernate.Query.class).setResultTransformer(Transformers.aliasToBean(DepartmentDTO.class)).list();

当我获得列表的大小时,它会给我正确的结果,但它会给出具有空值的部门列表,如

(在数据库中,我有3个部门)

输出

[
  {
    "id": null,
    "name": null,
    "setOfEmployee": null
  },
  {
    "id": null,
    "name": null,
    "setOfEmployee": null
  },
  {
    "id": null,
    "name": null,
    "setOfEmployee": null
  }
]

我得到的所有字段都是空值。

那么问题是什么,使用ResultTransformer有什么错误?或者是执行此查询的更好方法,我可以使用DTO获取记录。?

0 个答案:

没有答案