为了账号安全,请及时绑定邮箱和手机立即绑定

如何仅从关系中检索属性而不是实体?

如何仅从关系中检索属性而不是实体?

米琪卡哇伊 2021-10-20 14:41:28
我正在 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;}我的休息 api 返回这个:{    employeeId:1,     employeeName:"Jhon",    department: { departmentId:1, departmentName:"IT"}}我想要的输出是: {    employeeId:1,     employeeName:"Jhon",    department: "IT" }我尝试返回一个 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}
查看完整描述

2 回答

?
万千封印

TA贡献1891条经验 获得超3个赞

这是因为我得到了一个空的 json:我的 Dto 类没有公共 getter 和 setter。解决方案是公开 Dto 字段或添加公共 getter/setter。


Class EmployeeDto{

    public Integer employeeId; 

    public String employeeName; 

    public String department;

}


查看完整回答
反对 回复 2021-10-20
  • 2 回答
  • 0 关注
  • 129 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信