实体对象未被持久化:通过未标记的关系找到新对象

时间:2012-05-13 16:31:46

标签: jpa persistence eclipselink

我试图坚持以下实体:

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;
}

为什么会这样? UserEntity是:

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

1 个答案:

答案 0 :(得分:1)

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

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