java - 在 Spring Boot 项目中,我想建立一对多的关系,但我对休息输出感到困惑
问题描述
我使用spring boot,spring data JPA创建了一个项目。在那个项目中,我ManyToOne
在运行项目时在该双向关系中使用了 Employee 和 Department 实体,这是一个意想不到的结果 Employee.java
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstname;
private String lastname;
private Long mobile;
private String email;
@ManyToOne
private Department department;
public Employee(Long id, String firstname, Department department) {
this.id = id;
this.firstname = firstname;
this.department = department;
}}
部门.java
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String Departmentname;
private String Address;
@OneToMany(mappedBy = "department",fetch = FetchType.EAGER)
private List<Employee>employees= new ArrayList<>();
public Department(String departmentname, String address) {
Departmentname = departmentname;
Address = address;
}
public void addEmployees(Employee employee)
{
this.employees.add(employee);
}
public void removeEmployees(Employee employee)
{
this.employees.remove(employee);
}
}
EmployeeRepository.java(I)
@Repository
public interface EmployeeRepositroy extends JpaRepository<Employee, Long> {
@Query("SELECT e FROM Employee e join e.department WHERE e.firstname =:n")
public List<Employee> getName(@Param("n") String firstname);
@Query("SELECT e FROM Employee e")
public List<Employee> getData();
}
EmployeeController.java
@RestController
public class EmployeeController {
@Autowired
EmployeeRepositroy employeeRepositroy;
@GetMapping("/record/{name}")
public Object GetNameByRecords(@PathVariable("name") String firstname)
{
return employeeRepositroy.getName(firstname);
}
}
错误在这里https://docs.google.com/document/d/1fD5eChDowY7F8tAE4ORM_V7ulSt6vHe23SKmkx22M18/edit?usp=sharing
解决方案
尝试返回对象时,您有无限递归。当 Jackson 尝试序列化您的返回对象时,它将卡在 Employee 和 Department 之间的循环引用上。您需要用@JsonIgnore 标记其中之一。部门中的员工列表或员工中的部门字段。
推荐阅读
- mysql - Sql查询不返回在不同表的列中具有特定值的用户
- html - 按钮标签的这些 HTML 属性是什么意思?
- android - 如何将文件夹的所有文件上传到Android中的Web服务器?
- wordpress - 用户注册终极会员时提交的密码如何获取?
- python - 当给定方法不存在时调用类中的另一个方法?
- flutter - 从嵌套的子视图颤振飞镖通知 AppBar
- azure-data-studio - 在 Azure Data Studio 中,查询都是断开的
- get - 如何将 Body-> Raw 中的查询转换为 url 中的查询字符串
- reactjs - 如果没有 React-hooks 和使用类组件而不是函数式组件,这个 React 代码会如何?
- wpf - 什么是违反类亲和力的例子?