H5W3
当前位置:H5W3 > java > 正文

【Java】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

本文地址:H5W3 » 【Java】jpa中使用多对多manyToManay,关于懒加载的出错问题

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址