我怎样才能从关系中只检索一个属性而不是实体?

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

我正在 Netbeans 中开发一个 maven web 应用程序项目,我有以下 类:

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

并且:

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

我休息apireturn这个:

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

我想要的输出是:

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

我尝试 return 一个 DTO,但我得到一个空 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}

使用命名查询

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

您可以在 NamedQueries 上找到更多信息:

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

这是因为我得到一个空 json:我的 Dto class 没有 public getter 和 setter。 解决方案是使 Dto 字段 public 或添加 public getters/setters.

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