我正在尝试在休眠中延迟加载实体,但无法克服上述错误。我基本上在玩 2 个实体:用户和角色:
public class User implements Serializeable {
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "T_USER_ROLE", joinColumns = @JoinColumn(name = "USER_ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID"))
private Set<Role> roles = new HashSet<Role>();
}
public class Role implements Serializeable { }
然后我有一个创建 User 实体的操作 bean,我们称之为方法 1:
user.getRoles().add(roleService.findByName(RolesEnum.ADMIN.toString()));
em.persist(user);
然后我尝试在设置角色和更新之前先保留用户实体,但它也失败了:
userService.create(user);
User user = userService.findById(user.getId());
Set<Role> roles = new HashSet<Role>();
roles.add(roleService.findByName(RolesEnum.MEMBER.toString()));
user.setRoles(roles);
userService.update(user, true);
注意:
- userService.create = 坚持
- userService.update = 合并
- 成员角色已存在于角色表中
- 我还尝试获取角色: entity.getRoles();
以下是完整的错误日志:
java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.test.Role org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1374)