Search code examples
javamysqlhibernatemany-to-many

How to deal with unique field generated by hibernate?


Getting right to the point, I'm trying to build the following logic to hibernate relationships.

A Resource has many read groups.

A Resource has many write groups.

Both groups are Groups class.

What I did until now:

ResourcePage.class

public class ResourcePage {
  /*
  useless code
  */
  private Set read;
  private Set write;
  @OneToMany(cascade = CascadeType.ALL,
    fetch = FetchType.EAGER,
    targetEntity = Groups.class)
  @JoinTable(name = "resourcepage_read_permissions")
  public Set getRead() {
    return read;
  }

  @OneToMany(cascade = CascadeType.ALL,
    fetch = FetchType.EAGER,
    targetEntity = Groups.class)
  @JoinTable(name = "resourcepage_write_permissions")
  public Set getWrite() {
    return write;
  }
  /*
  useless code
  */    
}

The tables is created as expected.

enter image description here

However, hibernate is generating an unique constraint to id of group and this is giving me a big problem because sometimes two different resources can be same group as read group.

enter image description here

How do you guys deal with it? How can I make hibernate not generate this unique constraint?

Thanks a lot.


Solution

  • You need to use @ManyToMany instead of @OneToMany.