Posted on Aug 26, 2008

Hibernate Bi-Directional Many-To-Many

This took me a few hours to figure out so I’m logging this here for my own sanity. If you have a bidirectional many-to-many mapping in Hibernate with a join table, the join table is only updated when the noninverse side of the mapping is inserted/updated. In the example below, the join table (pane_specs) is only updated when a spec is saved, not when a pane is saved:

Spec.java

@ManyToMany
@JoinTable(
name = “pane_specs”,
joinColumns = { @JoinColumn(name = “spec_id”) },
inverseJoinColumns = { @JoinColumn(name = “pane_id”) }
)
public List<Pane> getPanes() {

Pane.java

@ManyToMany(mappedBy = “panes”)
public List<Spec> getSpecs() {

2 Comments