两个实体类
User
@Data @Entity @Table(name = "sys_user") public class User { @Id @GeneratedValue @Column(name = "user_id") private Integer userId; @Column(name = "username") private String username; @ManyToMany(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY) @JoinTable( name = "user_role", joinColumns = {@JoinColumn(name = "user_id")}, inverseJoinColumns = {@JoinColumn(name = "role_id")} ) private Set<Role> roles; }
Role
@Data @Entity @Table(name = "sys_role") public class Role { @Id @Column(name = "role_id") private Integer roleId; @Column(name = "role_name", unique = true) private String roleName; @ManyToMany(cascade = {CascadeType.ALL}, fetch = FetchType.LAZY, mappedBy = "roles") private Set<User> users;
测试代码
@Transactional @Test public void save() throws Exception{ Set<Role>roles = new HashSet<Role>(); roles.add(new Role(1, "USER")); roles.add(new Role(2, "ADMIN")); repository.save(new User("张三", roles)); } @Transactional @Test public void findAll(){ List<User> users = repository.findAll(); for (User user : users) { System.out.println(user); } }
在使用插入数据的时候没有任何问题,但是当查询的时候报错
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: wang.xiaoqiang.manytomany.entity.User.roles, could not initialize proxy - no Session
这个可以理解,懒加载的时候丢失了session无法获取roles信息,当将user中的集合设置为急加载模式,结果就遇到StackOverflowError
哪位大佬有相关经历,帮帮忙。。。
特南克斯
相关分类