实体对象未持久化:通过未标记的关系找到了新对象 [英] Entity Object Not Getting Persisted: New object was found through a relationship that was not marked
问题描述
我正在尝试保留以下实体:
I am trying to persist the following entity:
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.
During synchronization a new object was found through a relationship that was not marked cascade PERSIST: entity.PostEntity@16afec.
当我尝试保留PostEntity时,它将被保留.没有抛出这样的异常:
when I try to persist PostEntity, it is persisted. No such exception is thrown:
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是:
Why it is happening? UserEntity is:
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:
I am persisting commentEntity using the code:
entityManagerFactory = Persistence
.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
entityManager = entityManagerFactory.createEntityManager();
entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
entityManager.persist(commentEntity);
entityTransaction.commit();
entityManager.close();
我不知道可能是什么原因?然后为什么PostEntity在相同情况下会持续存在?
I am not able to understand what can be the cause? And then why PostEntity is getting persisted in the same situation?
我正在使用EclipseLink
I am using EclipseLink
推荐答案
因为您尝试保留具有userEntity或postEntity(或两者)引用未持久实体的CommentEntity.调用 em.persist(commentEntity的实例)不会导致这些实体被持久化,因为您只能级联刷新.您应该通过分别调用 em.persist .
Because you try to persist CommentEntity that have either userEntity or postEntity (or both) referencing to the entity that is not persisted. Call to em.persist(instance of commentEntity) does not cause those entities to be persisted, because you cascaded only refresh. You should persist those entities with separate calls to em.persist.
如果这不能回答您的问题,请提供创建实体并将其持久化的代码.
If this does not answer to your question, please provide the code that creates entities and persists them.
这篇关于实体对象未持久化:通过未标记的关系找到了新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!