我正在尝试保留以下实体:
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