OneToMany获取懒惰不使用spring boot + JPA

时间:2018-04-04 08:57:04

标签: spring-data-jpa fetch lazy-initialization

我有两个实体。学生和部门。一个部门有很多学生。我指定了抓取类型lazy。当我试图仅获取部门实体时,它也会显示学生数据。

 @Entity(name = "tbl_department")
public class DepartmentEntity implements Serializable {

private static final long serialVersionUID = 1560990434803170482L;

@Id
@GeneratedValue
private Integer id;

@NotNull(message = "Department name can not be null")
private String departmentName;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "department", fetch = FetchType.LAZY)
private Set<StudentEntity> studentList;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getDepartmentName() {
    return departmentName;
}

public void setDepartmentName(String departmentName) {
    this.departmentName = departmentName;
}

public Set<StudentEntity> getStudentList() {
    return studentList;
}

public void setStudentList(Set<StudentEntity> studentList) {
    this.studentList = studentList;
}


 @Entity(name = "tbl_student")
 public class StudentEntity implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 2969421115938100526L;

@Id
@GeneratedValue
private Integer id;

@NotNull(message = "First Name Can not null")
private String firstName;

@NotNull(message = "Last Name Can not null")
private String lastName;

@NotNull(message = "Date Of Birth Can not null")
private Date dateOfBirth;

private Integer age;

@NotNull(message = "Address Can not null")
private String address;

@JsonIgnore
@ManyToOne(cascade = CascadeType.ALL)
private DepartmentEntity department;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public Date getDateOfBirth() {
    return dateOfBirth;
}

public void setDateOfBirth(Date dateOfBirth) {
    this.dateOfBirth = dateOfBirth;
}

public Integer getAge() {
    return age;
}

public void setAge(Integer age) {
    this.age = age;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public DepartmentEntity getDepartment() {
    return department;
}

public void setDepartment(DepartmentEntity department) {
    this.department = department;
}

因此,当我尝试使用departmentRepo获取部门实体时,即使我指定了抓取类型lazy,它也会显示所有映射到该部门的学生

1 个答案:

答案 0 :(得分:0)

您可以将您的实体声明如下,然后尝试一次

学生实体:

@OrderBy("id ASC")
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="departmentid")
@JsonIgnore
private Department department;

部门实体:

@OrderBy("id ASC")
@OneToMany(fetch=FetchType.LAZY, mappedBy="department")
 private Set<Student> students = new LinkedHashSet<Student>(0);