这个问题肯定是由于关联表之间加载方式配置不当引起的(这不是废话么),网上有很多是关于“一对多”和“多对一”引起的错误的解决方案,我这里说一下,我遇到的是“多对多”
修改前
// UserInfo
@ManyToMany(cascade=CascadeType.REFRESH, fetch = FetchType.LAZY)
@JoinTable(
name="user_role",
joinColumns=@JoinColumn(name="user_id"),
inverseJoinColumns=@JoinColumn(name="role_id")
)
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
// Role
@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST}, fetch = FetchType.LAZY)
@JoinTable(
name="user_role",
joinColumns=@JoinColumn(name="role_id"),
inverseJoinColumns=@JoinColumn(name="user_id"))
public List<UserInfo> getUserInfos() {
return userInfos;
}
public void setUserInfos(List<UserInfo> userInfos) {
this.userInfos = userInfos;
}
修改后
// UserInfo
@ManyToMany(cascade=CascadeType.REFRESH, fetch = FetchType.EAGER)
@JoinTable(
name="user_role",
joinColumns=@JoinColumn(name="user_id"),
inverseJoinColumns=@JoinColumn(name="role_id")
)
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
// Role
@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST}, fetch = FetchType.LAZY,
targetEntity = UserInfo.class)
@JoinTable(
name="user_role",
joinColumns=@JoinColumn(name="role_id"),
inverseJoinColumns=@JoinColumn(name="user_id"))
public List<UserInfo> getUserInfos() {
return userInfos;
}
public void setUserInfos(List<UserInfo> userInfos) {
this.userInfos = userInfos;
}
引起问题的主要原因是因为UserInfo中关于到Role的加载策略使用了懒加载,结果在登录成功后就获取User对应Role时就出现在 org.hibernate.LazyInitializationException: failed to lazily initialize XXXXX could not initialize proxy - no Session错误,只需要将懒加载改为急加载即可