Entity Object Not Getting Persisted: New object was found through a relationship that was not marked

爱⌒轻易说出口 提交于 2020-01-06 19:56:00

问题


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;

}

But the error comes out:

During synchronization a new object was found through a relationship that was not marked cascade PERSIST: entity.PostEntity@16afec.

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

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

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();

I am not able to understand what can be the cause? And then why PostEntity is getting persisted in the same situation?

I am using EclipseLink


回答1:


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.



来源:https://stackoverflow.com/questions/10573345/entity-object-not-getting-persisted-new-object-was-found-through-a-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!