如何使用Spring Data jpa的OneToMany属性和FetchType Lazy配置来获取数据

问题描述 投票:0回答:1

有人可以帮忙解决这个问题吗?我有一个名为 Staff 的实体,其属性 adminStaffResponses 将为 OneToMany 映射创建一个单独的表。我故意将 FetchType 配置为 Lazy,如何通过员工 ID 和分页来获取 StaffRequests 列表。

这是职员班

package com.oouweb.staffrequestapp.model.entity;

import com.oouweb.staffrequestapp.model.constant.StaffType;
import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Data
@NoArgsConstructor
@Entity
@Table(name = "staffs")
public class Staff {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(nullable = false, unique = true)
    private String staffId;

    @Column(nullable = false, length = 25)
    private String firstName;

    @Column(nullable = false)
    private String lastName;

    @Column(nullable = false, length = 25)
    private String middleName;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String encryptedPassword;

    @Enumerated(EnumType.STRING)
    private StaffType staffType;

    @Column(nullable = true)
    private String profilePicturePathId;

    @Column(name = "is_valid")
    private boolean isValid;

    @Column(nullable = false, length = 14)
    private String phoneNumber;

    @Temporal(TemporalType.TIMESTAMP)
    private Date dateCreated;

    @ManyToOne(fetch = FetchType.EAGER)
    private Department department;

    @ManyToOne(fetch = FetchType.EAGER)
    private NonAcademicUnit nonAcademicUnit;

    @OneToMany(fetch = FetchType.LAZY)
    private List<StaffRequest> staffRequests = new ArrayList<>();

    @OneToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "admin_staff_responses",
            joinColumns = @JoinColumn(name = "staff_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "request_id")
    )
    private List<StaffRequest> adminStaffResponses = new ArrayList<>();

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name = "staff_roles",
            joinColumns = @JoinColumn(name = "staffId", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "roleId", referencedColumnName = "id")
    )

在此输入


    private List<Role> roles = new ArrayList<>();

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Staff staff = (Staff) o;
        return id == staff.id;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id);
    }
}

这个

package com.oouweb.staffrequestapp.model.entity;

import com.oouweb.staffrequestapp.model.constant.RequestResponseStatus;
import com.oouweb.staffrequestapp.model.constant.RequestStatus;
import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Data
@NoArgsConstructor
@Entity
@Table(name = "staff_requests")
public class StaffRequest {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(nullable = false)
    private String requestId;

    @Column(nullable = false)
    private String requestSubject;

    @Column(length = 1000)
    private String reasonForRequest;

    private String attachmentUrl;

    @Enumerated(EnumType.STRING)
    private RequestStatus requestStatus;

    @Enumerated(EnumType.STRING)
    private RequestResponseStatus responseStatus;

    @OneToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "admin_request_reviews  ")
    List<RequestReview> reviews = new ArrayList<>();

    @Temporal(TemporalType.DATE)
    private Date requestDate;

    @ManyToOne(fetch = FetchType.EAGER)
    private Staff staff;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StaffRequest that = (StaffRequest) o;
        return id == that.id;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(id);
    }
}
`

I tried to use native query not but it was bringing ambiguous attribute

`@Query(value = """
            SELECT id, request_id, request_subject, reason_for_request, attachment_url, request_status,                        response_status, request_date
            FROM[tag:tag-name]
            admin_staff_responses asr
            JOIN
            staff_requests sr
            ON
            asr.request_id = sr.id
            WHERE
            asr.staff_id = :staffId
          """, nativeQuery = true)
    List<StaffRequest> findByStaff(int staffId);`
java spring hibernate jpa jpql
1个回答
0
投票

根据实现,当程序代码使用惰性定义的关系时,它们会自动加载。与此同时,他们被代理。请参阅此说明:https://backendhance.com/en/blog/2023/jpa-fetching-strategies/#lazy-loading

要使用分页,您可能应该阅读https://thorben-janssen.com/pagination-jpa-hibernate/

分页在一定程度上是可定制的。

© www.soinside.com 2019 - 2024. All rights reserved.