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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With