Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ManyToMany relation not save

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.

like image 362
Arch Avatar asked Nov 30 '22 16:11

Arch


2 Answers

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.

like image 200
Dragan Bozanovic Avatar answered Dec 05 '22 10:12

Dragan Bozanovic


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.

like image 39
Master Slave Avatar answered Dec 05 '22 12:12

Master Slave