首页 > 解决方案 > 在 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

标签: javaspring-bootspring-data-jpahibernate-mapping

解决方案


尝试返回对象时,您有无限递归。当 Jackson 尝试序列化您的返回对象时,它将卡在 Employee 和 Department 之间的循环引用上。您需要用@JsonIgnore 标记其中之一。部门中的员工列表或员工中的部门字段。


推荐阅读