当使用JPA持久化父对象时,如何防止保存子对象?"瞬态属性值异常 "报告。

问题描述 投票:0回答:1

我有一个父实体-Parent和一个子实体-Child的一对一关系,我对实体使用双向映射。

如何保存父实体而不保存子实体,因为子实体被设计为只读列?当持久化父实体对象时,会报告瞬态错误。 org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : test.spring.business.Parent.child。

我不能使用transient,因为我需要数据库中的子实体。

@Entity
@Table(name = "parent")
@SequenceGenerator(name = "SEQUENCE_FACTORY", sequenceName = "SEQ_ID", schema = "REQ", allocationSize = 1)
public class Parent implements Serializable {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQUENCE_FACTORY")
    private Long id;

    @OneToOne(mappedBy="parent")
    public Child child;

    // ...
}


@Entity
@Table(name = "child")
public class Child implements Serializable{

    @Id
    @OneToOne(optional = false,fetch = FetchType.LAZY)
    @JoinColumn(name="parent_id",insertable=false,updatable=false)
    private Parent parent;
    // ...
    private Long checkData;

}


@Transactional
public void testParent()
{
    Parent p=new Parent();
    p.child= new Child();
    // ...
    //p.child get input...
    //...
    entityManager.persist(p);

    if(p.child.checkData>n)
    {
        p.child.setParent(p);
        entityManager.persist(p.child);
    }

}
java hibernate jpa-2.0
1个回答
0
投票

由于 Child 实例是 new/transient 你会遇到这个错误。这说明hibernate不知道父节点在DB中关联到哪个子节点。

由于子代是只读的,所以将测试改为

@Transactional
public void testParent()
{
    Parent p=new Parent();
    p.child= entityManager.find(Child.class, 100L);
    entityManager.persist(p);

}
© www.soinside.com 2019 - 2024. All rights reserved.