Using Entity Graph with DTO Projection using ResultTransformer returns null value

1.6k Views Asked by At

Hello I am new in jpa + criteria API + hibernate..

I have doubt related to use of ResultTransformer in jpa criteria API.

I am having two entity Department and Employee. one to many mapping between department and employee. i want to use entitygraph with DTO projection

1. Department

@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. Employee

@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();

when i will get size of list it will give me correct result but it will give list of department with null value like

(In database i am having total 3 departments)

Output :

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

I am getting all fields with null value.

So what is the issue here , is any mistake in use of ResultTransformer? Or is any better way to execute this query where I can get records using DTO ..?

0

There are 0 best solutions below