@ManyToMany relation not save

假如想象 提交于 2020-01-11 06:33:27

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/36239030/manytomany-relation-not-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!