【问题标题】:Entity Object Not Getting Persisted: New object was found through a relationship that was not marked实体对象未持久化:通过未标记的关系找到新对象
【发布时间】:2013-01-19 00:37:58
【问题描述】:

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

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

【问题讨论】:

    标签: jpa persistence eclipselink


    【解决方案1】:

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

    如果这不能回答您的问题,请提供创建实体并将其持久化的代码。

    【讨论】:

    • 您已编辑,但仍然没有显示 CommentEntity 引用的内容(如果有的话),当它被持久化时。由于它的关系未设置为全部级联,因此如果它引用任何新实体(例如 postEntity 的新实例,它们不会持久化。而如果你持久化 postEntity,它会级联到新的 CommentEntity 的关系。持久化所有实体之前设置关系或更改您的级联设置,以便持久级联到所有必需的新实体。
    猜你喜欢
    • 1970-01-01
    • 2012-07-28
    • 2015-07-27
    • 2011-02-05
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    相关资源
    最近更新 更多