1
votes

I'm trying to persist new entity Parent with the child that already exists in db. I don't want to update child during persistence of parent but just want to create a relationship. When I'm sending json from frontend it looks like this:

{ "child": { "id": 3 } }

On save I'm getting :

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

@Entity
class Parent {
    @ManyToOne(optional = false)
    @JoinColumn(name = "CHILD_ID", referencedColumnName = "CHILD_ID")
    private Child child;
}

@Entity
class Child {
    @Id
    @Column(name="CHILD_ID")
    private Long id;
}
3

3 Answers

1
votes
@Entity
class Parent {
    @ManyToOne(optional = false,  cascade = CascadeType.SAVED_UPDATE)
    @JoinColumn(name = "CHILD_ID", referencedColumnName = "CHILD_ID")
    private Child child;
}
0
votes

use child_id to load existing child object, and then set inject it to parent and save parent.

0
votes

You can't. Either make your @manyToOne annotation optional attribute true or retrieve a proxy instance of your child and set it to your parent.