0

我正在尝试保留以下实体:

public class CommentEntity {

@Id

@ManyToOne(optional=false,cascade=CascadeType.REFRESH, targetEntity=UserEntity.class)
@JoinColumn(name="USERID",referencedColumnName="USERID")
private UserEntity userEntity;

@ManyToOne(optional=false,cascade=CascadeType.REFRESH, targetEntity=PostEntity.class)
@JoinColumn(name="POSTID",referencedColumnName="POSTID")
private PostEntity postEntity;

}

但是错误出来了:

在同步期间,通过未标记为级联 PERSIST 的关系找到了一个新对象:entity.PostEntity@16afec。

当我尝试持久化 PostEntity 时,它会持久化。不会抛出这样的异常:

public class PostEntity {

@ManyToOne(optional = false, cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, targetEntity = UserEntity.class)
@JoinColumn(name = "USERID", referencedColumnName = "USERID")
private UserEntity userEntity;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "postEntity", fetch = FetchType.LAZY)
private List<CommentEntity> commentEntityList;
}

为什么会这样?用户实体是:

public class UserEntity {

@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "userEntity")
private List<PostEntity> postEntityList;

@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "userEntity")
private List<CommentEntity> commentEntityList;
}

我正在使用代码坚持commentEntity:

entityManagerFactory = Persistence
                    .createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
            entityManager = entityManagerFactory.createEntityManager();
            entityTransaction = entityManager.getTransaction();
            entityTransaction.begin();
            entityManager.persist(commentEntity);
            entityTransaction.commit();
            entityManager.close();

我无法理解可能是什么原因?那么为什么 PostEntity 会在同样的情况下持续存在呢?

我正在使用 EclipseLink

4

1 回答 1

2

因为您尝试保留具有 userEntity 或 postEntity(或两者)引用未持久化实体的 CommentEntity。调用em.persist(instance of commentEntity)不会导致这些实体被持久化,因为您级联只刷新。您应该通过单独调用em.persist来持久化这些实体。

如果这不能回答您的问题,请提供创建实体并保留它们的代码。

于 2012-05-13T16:42:07.873 回答