简体   繁体   中英

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}

Using NamedQueries

@Entity
@Table(name="employees")
@NamedQueries({
    @NamedQuery(
        name = "getDesiredUser",
        query = "SELECT e.employeeId, e.employeeName, d.departmentName FROM employees AS e INNER JOIN departments as d ON e.department_id = d.departmentId"),

})
public class Employee {
    @Id
..
}

You can find more on NamedQueries :

https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-creating-database-queries-with-named-queries/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM