如何用Spring JPA连接表来创建嵌套对象?

c3frrgcw  于 2023-03-02  发布在  Spring
关注(0)|答案(1)|浏览(145)

我尝试用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错误。任何帮助都是感激的。

prdp8dxp

prdp8dxp1#

This Projection worked for me for the native query
    SELECT department.department_name as deptName,
     department.department_desc as deptDesc, 
    employee.employee_id empId,  
    employee.employee_name empName 
    FROM department
    JOIN employees 
    ON employees.department_id = department.department_id
    -----------------------------------------------------
    package mypackage;
    
    import org.springframework.beans.factory.annotation.Value;
    
    public interface EmpDeptDTO {
        String getEmpId();
        String getEmpDesc();
        @Value("#{@departmentMapper.buildDepartmentDTO(target.deptName, target.deptDesc)}")
        DepartmentDTO getDepartment();
    }
    
    --------------------------------------
    import lombok.Data;
    
    @Data
    public class DepartmentDTO {
        private String deptName;
        private String deptDesc;
    }
---------------------------------
@Component
public class DeparmentMapper {
public DepartmentDTO buildDepartmentDTO(String deptName, String deptDesc) {
        DepartmentDTO  deptDTO= new DepartmentDTO ();
        deptDTO.setDeptName(deptName);
        deptDTO.setDeptDesc(deptDesc);
        return deptDTO;
    }
}

相关问题