欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate 错误:org.hibernate.LazyInitializationException: failed to lazily initial

程序员文章站 2022-03-02 13:25:18
...
有两张多对多关联表:

@Entity
@AccessType("field")
@Table(name="MENU")
public class Menu implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@Column(name="menu_id")
private Long menuId;

@Column(name="menu_Name")
private String menuName;

/**
* 角色-菜单关联
*/
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch=FetchType.LAZY)//合并
@JoinTable(name = "ROLE_MENU", joinColumns = { @JoinColumn(name = "menu_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") })
// @PersistenceContext(type = PersistenceContextType.EXTENDED)
private Set<Role> roles = new LinkedHashSet<Role>();

public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}



@Entity
@AccessType("field")
@Table(name="ROLE")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@Column(name="role_id")
private Long roleId;

@Column(name="role_Name")
private String roleName;


/**
* 角色-菜单关联
*/
@ManyToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.LAZY)
@JoinTable(name = "ROLE_MENU", joinColumns = { @JoinColumn(name = "role_id") }, inverseJoinColumns = { @JoinColumn(name = "menu_id") })
private Set<Menu> menus = new LinkedHashSet<Menu>();

public Set<Menu> getMenus() {
return menus;
}
public void setMenus(Set<Menu> menus) {
this.menus = menus;
}
}


注意:一定要两张表分别@JoinTable(name = "ROLE_MENU")

在Role在引用menus的时候,报:org.hibernate.LazyInitializationException: failed to lazily initial

解决办法:roleDao.getHibernateTemplate().initialize(role.getMenus());


当关联表中不存在此记录时,role.getMenus();将会报错:org.hibernate.ObjectNotFoundException: No row with the given identifier exists:

解决办法:加上 @NotFound(action = NotFoundAction.IGNORE)