[英]Spring JPA Exposing/Mapping @JsonIgnore fields from an associated Entity using custom query @Query
我有 2 个具有双向一对多关系的实体(部门、员工)。 1个部门有很多员工。 Department
拥有Employee
我用@JsonIgnore
注释了department
字段,以便在我GET localhost:8080/employee
时不会序列化Department
信息
我创建了一个自定义查询来公开Employee
的所有信息,包括员工所属的Department
。
部门Model
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String departmentName;
@OneToMany(mappedBy = "department")
private Set<Employee> employees;
...
}
员工Model
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String middleName;
private String lastName;
@ManyToOne
@JsonIgnore
private Department department;
...
}
存储库
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
@Query(value = "SELECT e.*, d.department_name FROM Employee e INNER JOIN Department d ON e.department_id = d.id WHERE e.id = ?1", nativeQuery = true)
Employee findEmployeeByIdWithDepartment(Long employeeId);
}
该查询在 H2-Console SQL 编辑器中运行良好。 如果我执行GET localhost:8080/employee/1
,则会包含DEPARTMENT_ID
, DEPARTMENT_NAME
信息
但是,在 Postman 中,我只获取Employee
信息(id、firstname、lastname、middlename)。 Employee
所属的Department
没有被映射/序列化(因为我在Employee
类中使用@JsonIgnored
)。
{
"id": 1,
"firstName": "John",
"middleName": "Doe",
"lastName": "Johnny"
}
如果我将Object
findEmployeeByIdWithDepartment
我可以获得Employee
信息以及员工所属的Department
。
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
@Query(value = "SELECT e.*, d.department_name FROM Employee e INNER JOIN Department d ON e.department_id = d.id WHERE e.id = ?1", nativeQuery = true)
Object findEmployeeByIdWithDepartment(Long employeeId);
}
结果:(不是嵌套Department
信息的所需 JSON 格式)
[
1,
"John",
"Johnny",
"Doe",
1,
"Accounting"
]
如果我执行GET localhost:8080/employee/1
并且仍然能够毫无问题地执行GET localhost:8080/department
,我不确定如何能够显示Department
信息和Employee
信息。
如果department
字段 IN Employee
class 中没有@JsonIgnore
,则 Json 响应将导致 StackOverflow 或 Endless 嵌套序列化问题。
谢谢你。
您可以为 Employee 中的 Depertment-properties 编写 getter,例如
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String middleName;
private String lastName;
@ManyToOne
@JsonIgnore
private Department department;
@JsonProperty("departmentId")
public Long getDepartmentId()
{
return department.getId;
}
@JsonProperty("departmentName")
public String getDepartmentName()
{
return department.getName();
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.