This is a mirror of official site: http://jasper-net.blogspot.com/

Hibernate Many-To-Many Revisited

| Wednesday, February 24, 2010
The modeling problem is classic: you have two entities, say Users and Roles, which have a many-to-many relationship with one another. In other words, each user can be in multiple roles, and each role can have multiple users associated with it.

The schema is pretty standard and would look like:

CREATE TABLE app_user (
  id INTEGER,
  PRIMARY KEY ( id ) );

CREATE TABLE app_role (
  id INTEGER,
  PRIMARY KEY ( id ) );

CREATE TABLE app_user_role (
  user_id INTEGER,
  role_id INTEGER,
  PRIMARY KEY ( user_id, role_id ),
  FOREIGN KEY ( user_id ) REFERENCES app_user ( id ),
  FOREIGN KEY ( role_id ) REFERENCES app_role ( id ) );

But there are really two choices for how you want to expose this at the Hibernate / EJB3 layer. The first strategy employs the use of the @ManyToMany annotation:

@Entity
@Table(name = "APP_USER")
public class User {
   @Id
   private Integer id;

   @ManyToMany
   @JoinTable(name = "APP_USER_ROLE",
      joinColumns = { @JoinColumn(name = "USER_ID") },
      inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
   private java.util.Set roles = new HashSet();
}

@Entity
@Table(name = "APP_ROLE")
public class Role {
   @Id
   private Integer id;

   @ManyToMany(mappedBy = "roles")
   private java.util.Set users = new HashSet();
}

The second strategy uses a set of @ManyToOne mappings and requires the creation of a third “mapping” entity

Read more: JBoss Community

Posted via email from jasper22's posterous

0 comments: