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什么的....
貌似网上的答案都不管用了!!
有解决方法吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,加过滤器解决懒加载问题;
内存溢出是因为陷入了死循环,一个department引出多个company属性,company又加载department集合,department又加载集合……
在集合属性前加个@JsonIgnore