3

您好,我是 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

}

部门DTO.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 获取记录 ..?

4

0 回答 0