Skip to content

Generating a primary key in @ManyToMany with hbm-ddl

Say, you have two entities which have a many to many relationship (Foo and Bar). Using JPA/Hibernate, they are mapped like this, with the owning entity being Foo.

public class Foo {
  ........

@ManyToMany
@JoinTable(name="foos_bars", joinColumns = { @JoinColumn(name = "foo_id") },
   inverseJoinColumns = { @JoinColumn(name = "bar_id") })
   public List<bar> getBars() {
      return bars;
   }
public class Bar {
 .....
@ManyToMany(mappedBy="foos")
   public List<foo> getFoos() {
      return foos;
   }
}

Using hibernate.hbm2ddl.auto= create-update, the table generated will have only two foreign keys (foo_id and bar_id) but no Primary key of it’s own. This would be a problem if you have database standards of enforcing referential integrities for every table.

However, there is an alternative. By changing the owning side of the many-many to a Set, you can generate a table that has a combined primary key;

@ManyToMany
@JoinTable(name="foos_bars", joinColumns = { @JoinColumn(name = "foo_id") },
   inverseJoinColumns = { @JoinColumn(name = "bar_id") })
   public Set<bar> getBars() {
      return bars;
   }

In this case, the table generates with the additional constraint, PRIMARY KEY (“FOO_ID”, “BAR_ID”). I haven’t found a way to generate a dedicated primary key but as long as your domain model doesn’t mind having a Set, there is no harm in going this approach of combined primary key

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*