object references an unsaved transient instance before save

  Kiến thức lập trình

I use spring boot 3.3.2 with jpa hibernate.

In a method transactional, I add pub to deposit, i add Actor to pub
not still calling save for the deposit and i get

object references an unsaved transient instance – save the transient instance before flushing : com.acme.pub.entity.Actor.pub -> com.acme.pub.entity.Pub

@Entity
public class Deposit {
    ...
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "deposit", cascade = {CascadeType.ALL})
    private List<Pub> pubs = new ArrayList<>(0);

    public void addPub(Pub pub) {
        pubs.add(pub);
        pub.setDeposit(this);
    }

    public void removePub(Pub pub) {
        pubs.remove(pub);
        pub.setDeposit(null);
    }

}


@Entity
public class Pub {
    ...
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "id_deposit", nullable = false)
    @NotNull
    protected Deposit deposit;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "pub", cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.REMOVE}, orphanRemoval = true)
    protected List<Actor> actors = new ArrayList<>(0);

    public void addActor(Actor actor) {
        actors.add(actor);
        actor.setPub(this);
    }

    public void removeActor(Actor actor) {
        actors.remove(actor);
        actor.setPub(null);
    }

}

@Entity
public class Actor {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "id_pub")
    private Pub pub;

}

I add pub in deposit via addPub,for Actor i use addActor

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT