保存延迟子导致:TransientObjectException:对象引用未保存的瞬态实例 - 在刷新之前保存瞬态实例

时间:2013-05-12 11:46:57

标签: hibernate jpa persistence

我正在试验hibernate中的延迟加载实体,但无法克服上面的错误。我基本上玩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 = persist
  • userService.update = merge
  • 角色表中已存在MEMBER角色
  • 我还尝试获取角色: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)

1 个答案:

答案 0 :(得分:0)

通过将实体管理器绑定到会话范围并使用seam-solder来解决此问题。

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE })
public @interface TempJpa { }

@ExtensionManaged
@ConversationScoped
@Produces
@PersistenceUnit(unitName="tempDataSource")
@TempJpa
private EntityManagerFactory emf;

@Inject
@TempJpa
protected EntityManager em;

但接下来的问题是为什么?