7

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.

Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110
Arch
  • 517
  • 2
  • 7
  • 17

3 Answers3

16

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.

Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110
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.

Master Slave
  • 27,771
  • 4
  • 57
  • 55
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.