为什么在ManyToOne关系中休眠FetchType.EAGER或fetch=FetchType.LAZY



在我的Spring Boot应用程序中,我使用hibernate。我有如下多对一关系:-

@Entity
@Table(name = "STUDENT")
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@Column
private int mobile;
@ManyToOne( fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "DEPT_ID", nullable = false)
private Department department;
public Long getId() {
return id;
}
public void setId(Long id){
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMobile() {
return mobile;
}
public void setMobile(int mobile) {
this.mobile = mobile;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + ''' +
", mobile=" + mobile +
", department=" + department +
'}';
}
}

作为:-

@Entity
@Table(name = "DEPARTMENT")
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@OneToMany(mappedBy = "department", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Student> studentList=new ArrayList<Student>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudentList() {
return studentList;
}
public void setStudentList(List<Student> studentList) {
this.studentList = studentList;
}
}

对于Department的fetch=FetchType.LAZY和fetch=FetchType.EAGER都运行良好。

为了更好地理解,我将Student的@ManyToOne(fetch=FetchType.EAGER(切换为@ManyToBone(fetch=FetchType.LAZY(。当FetchType.RAZY时,它会出现以下错误:-

"类型定义错误:[简单类型,类org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor];嵌套异常为com.fasterxml.jackson.databind.exc.InvalidDefinitionException:找不到类org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor的序列化程序,也找不到创建BeanSerializer的属性(为避免异常,请禁用SerializationFeature.FAIL_ON_EMPTY_BEANS((通过引用链:java.util.ArrayList[0]->com.myjavablog.model.Student["department"]->com.myjavablog.model.Department$HibernateProxy$w9HG3Rv0["hibernateLazyInitializer"](;

为什么会发生这种情况?为什么我不能为学生做那种懒散的事?提前感谢!

您可以忽略以通过生成属性的JSON输出

@JsonIgnore 

或者,如果您有任何具有关系的惰性加载属性。您可以在属性的顶部使用此注释。

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) 

这解决了我的问题。感谢社区的建议。

最新更新