我正在 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;
}
添加回答
举报
0/150
提交
取消