spring - jpa中使用多对多manyToManay,关于懒加载的出错问题
本文介绍了spring - jpa中使用多对多manyToManay,关于懒加载的出错问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
先看看Company实体类:主要代码
@Table(name = "ppp_corp")
@Entity
public class Company {
private Integer corpId;
private String corpName;
private Set<Department> depts = new HashSet<Department>();
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
public Integer getCorpId() {
return corpId;
}
@JoinTable(name = "company_department", joinColumns = {@JoinColumn(name = "Corp_ID", referencedColumnName = "corpId")}, inverseJoinColumns = {@JoinColumn(name = "Department_ID", referencedColumnName = "deptId")})
@ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
public Set<Department> getDepts() {
return depts;
}
然后是Department实体类
@Table(name = "ppp_department")
@Entity
public class Department {
private Integer deptId;
private String departName;
private Set<Company> corps = new HashSet<Company>();
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
public Integer getDeptId() {
return deptId;
}
@ManyToMany(mappedBy = "depts")
public Set<Company> getCorps() {
return corps;
}
生成后运行,就出现500错误,
com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.domain.Company.depts, could not initialize proxy - no Session
后来,在@ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)改为
@ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.eager)
就会出现内存溢出。提示-1
另外,在web.xml加上过滤器:也会出现内存溢出,提示-1
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter<filter-class>
因为spring用的是jap,所以用OpenEntityManagerInViewFilter。
我也试过用hibernate的rg.springframework.orm.hibernate5.support.OpenSessionInViewFilter
但是,也出错,没有noclass什么的....
貌似网上的答案都不管用了!!
有解决方法吗?
解决方案
首先,加过滤器解决懒加载问题;
内存溢出是因为陷入了死循环,一个department引出多个company属性,company又加载department集合,department又加载集合……
在集合属性前加个@JsonIgnore
这篇关于spring - jpa中使用多对多manyToManay,关于懒加载的出错问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文