我正在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;
}
我的rest 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}
答案 0 :(得分:0)
使用命名查询
@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上找到更多信息:
答案 1 :(得分:0)
这是因为我得到了一个空的json:我的Dto类没有公共的获取器和设置器。 解决方案是公开Dto字段或添加公共获取器/设置器。
{{1}}