我尝试用SpringJPA连接多个表,以便接收嵌套对象,但是我在存储库接口中设置的查询似乎有问题。
- 这是所需的输出(仅为简化示例)**
[departmentId: 1
departmentName: A
employees:[
[employeeId: 100
employeeName: John],
[employeeId: 200
employeeName: Carl]],
[departmentId: 2
departmentName: B
employees:[
[employeeId: 300
employeeName: Nancy]]
- 我在Postgres中有以下表格:**
部门:部门标识,部门名称
雇员:雇员标识、雇员姓名、部门标识
- 这些是我的课程**
- 部门**
@Entity
@Table(name="department")
public class Department implements Serializable {
@Id
@Column(name="department_id")
private Integer departmentId;
@Column(name="department_name")
private String departmentName;
@OneToMany(mappedBy = "department")
private List<Employee> employees;
}
//getters, setters, etc.
- 雇员**
@Entity
@Table(name="employees")
public class Employee implements Serializable {
@Id
@Column(name="employee_id")
private Integer employeeId;
@Column(name="employee_name")
private String employeeName;
@ManyToOne
@JoinColumn(name="department_id")
private Department department;
}
//getters, setters, etc.
- 存储库**
@Repository
public interface Repository extends JpaRepository<Department, Integer> {
@Query(value = "SELECT department.department_id, department_name, employee_id, employee_name FROM department " +
"JOIN employees ON employees.department_id = department.department_id", nativeQuery = true)
List<Department> findDeps();
}
但是我得到了一个LazyInitializationException。我读到过不推荐设置FetchType.EAGER,但是即使这样也会抛出StackOverFlow错误。任何帮助都是感激的。
1条答案
按热度按时间prdp8dxp1#