JPA N:M관계 설정 (@IdClass)

JPA N:M관계 설정 (@IdClass)

DB Table

  • User : id, user_name
  • Group : id, group_name
  • UserGroup(Mapping) : user_id, group_id

JAVA


// user domain

@Entity
@Table(name = "user")
public class User {
  
  @Id
  @Column(name="id")
  private int id;
  
  private String userName;
  
  @OneToMany(mappedBy = "user")
  private Collection<UserGroup> userGroupByUser;

  // ...getter and setter
}

// group domain

@Entity
@Table(name = "group")
public class Group {
  
  @Id
  @Column(name="id")
  private int id;
  
  private String groupName;
  
  @OneToMany(mappedBy = "group")
  private Collection<UserGroup> userGroupByGroup;

  // ...getter and setter
}

// user and group mapping domain


@Entity
@Table(name = "usergroup")
@IdClass(UserGroupPK.class)
public class UserGroup {
  
  @Id
  @ManyToOne
  @JoinColumn(name = "user_id", referencedColumnName = "id") //user_id
  private User user;
  
  @Id
  @Column(name="group_id")
  @JoinColumn(name = "group_id", referencedColumnName = "id") //group_id
  private Group group;

  // ...getter and setter
}

//UserGroupPK

public class UserGroupPK implements Serializable {
  
  private int user;
  private int group;
  
  public UserGroupPK() { }
  
  public UserGroupPK(int user, int group) { 
    this.user = user;
    this.group = group;
  }
  
  // ...getter and setter and equals and hashcode method
}