[英]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: 我正在Netbeans中从事Maven Web应用程序项目,我有以下课程:
@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: 我的休息API返回此:
{
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: 我尝试返回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: 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 : 您可以在NamedQueries上找到更多信息:
https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-creating-database-queries-with-named-queries/ 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. 这是因为我得到了一个空的json:我的Dto类没有公共的获取器和设置器。 The solution is to make the Dto fields public or add public getters/setters.
解决方案是公开Dto字段或添加公共获取者/设置者。
Class EmployeeDto{
public Integer employeeId;
public String employeeName;
public String department;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.