Julien
Julien

Reputation: 2756

Hibernate @OneToMany how to persist the relationship without updating the (many) elements?

I have

public class Stale {

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "stale", cascade = CascadeType.ALL)
    private List<Poney> poneys;
}

and

public class Poney {

    @ManyToOne()
    @JoinColumn(name = "stale_id")
    private Stale stale;

    private String name;
}

When I try to save a stale with an updated poney list, the persisting of a stale doesn't behave like I would it to do.

Can someone help me ?

Upvotes: 0

Views: 116

Answers (1)

Deltharis
Deltharis

Reputation: 2373

The problem is that this is a bi-directional relationship. When updating the state of a bidirectional relationship it is applications duty to update the state on both sides (so not only remove Ponies from Stable, but also remove the Stable reference in Ponies). That can be accomplished for example by @BeforePersist or @BeforeUpdate method in the Stable entity. Since Pony is the owner of the relationship JPA sees the state of Pony as more important than state of Stable, and removing ponies in Stable does nothing.

As for your last point - again, since this is bidirectional and Pony is the owner it's impossible to change the state of the relationship without saving new state of Pony (including any changes like name).

They way you want this to behave makes me think what you actually want is a uni-directional relationship on the Stable side:

@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name="stale_id", referencedColumnName="id")
private List<Poney> poneys;

And removing the @ManyToOne mapping in Pony.

Upvotes: 1

Related Questions