Search code examples
javajpajakarta-eeentityentitymanager

How can I retrieve only an attribute instead of the Entity from a relationship?


I'm working on a maven web application project in Netbeans and I have the following classes:

@Entity
@Table(name = "departments")
public class Department{
    @Id
    private Integer departmentId;
    @Column(name = "department_name")
    private String departmentName;
}

And:

@Entity
@Table(name = "employees")
public class Employee {
    @Id
    private Integer employeetId;
    @Column(name = "employee_name")
    private String employeeName;
    @JoinColumn(name = "department_id", referencedColumnName = 
    "department_id")
    @ManyToOne(optional = false)
    private Departments department;
}

My rest api return this:

{
    employeeId:1, 
    employeeName:"Jhon",
    department: { departmentId:1, departmentName:"IT"}
}

My desired output is:

 {
    employeeId:1, 
    employeeName:"Jhon",
    department: "IT"
 }

I try to return an DTO, but I get an empty json:

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<EmployeeDto> findAllEmployees() {
    CriteriaQuery cq = entityManager.getCriteriaBuilder().createQuery(Employee.class);
    cq.select(cq.from(Employee.class));
    List<Employee> employees = entityManager.createQuery(cq).getResultList();
    List<EmployeeDto> employeesDto = new ArrayList<>();

    for (Employee employee : employees) {
        EmployeeDto employeeDto = new EmployeeDto();
        employeeDto.employeeId = employee.getEmployeedId();
        employeeDto.department = employee.getDepartment().getDepartmentName();

        employeesDto.add(employeeDto);
    }
    return   employeesDto;

DTO:

Class EmployeeDto{Integer employeeId; String employeeName; String department}

Solution

  • This is because I get an empty json: My Dto class has not public getters and setters. The solution is to make the Dto fields public or add public getters/setters.

    Class EmployeeDto{
        public Integer employeeId; 
        public String employeeName; 
        public String department;
    }