@ManyToMany relation not save
Asked Answered
A

3

8

I have some entities with@ManyToMany relation:

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "buses_drivers",
        joinColumns = @JoinColumn (name = "driver_id_inner", referencedColumnName = "driver_id"),
        inverseJoinColumns = @JoinColumn (name = "bus_id_inner", referencedColumnName = "bus_id"))
private List<Bus> buses;

and

@ManyToMany(mappedBy = "buses", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Driver> drivers;

When execute saving Driver model with some Bus models, all ok. Tables buses_drivers store all keys those entities. But when saving Bus model with drivers, table doesn't change. I think problem with inverseJoinColmns mapping.

Ane answered 26/3, 2016 at 18:18 Comment(1)
or maybe the problem is in your persistence code? Perhaps posting it would help?Jadwigajae
L
17

That is the expected behaviour. In a bidirectional many-to-many association one side has to be the inverse side. In your case it is the Bus side because it contains mappedBy:

The field that owns the relationship. Required unless the relationship is unidirectional.

That means that Driver is the owner of the association and Hibernate will only check that side when maintaining the association.

Latrena answered 26/3, 2016 at 22:53 Comment(0)
M
8

You should definitely redesign your relations.

Without even getting into the problems with your current save scenario, with bidirectional @ManyToMany + CascadeType.ALL, you're destined to get even more troubles.

For example, deleting one bus will due to cascade, delete all its drivers, which due to cascade again, will delete all its buses. You'll basically end up deleting much more than you probably want. Also, check the SQL generated by these mappings, you'll most likely notice that its far from ideal.

Mateusz answered 26/3, 2016 at 18:41 Comment(0)
G
1

For people doesn't understand from the accepted answer. This is more appropriate : Java: saving entities with ManyToMany association

I came across with this problem in test cases when filling test data.

When there is an owning side you just can save child just with owner.

Granniah answered 7/9, 2022 at 10:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.