sideshowbob
sideshowbob

Reputation: 316

Hibernate 2 primary keys as foreign keys

I am new to hibernate so don't really know if I am doing this correctly. Here is my situation. I have a Person and a Group, A person has an ID and must belong to a group that also has an ID. The person can belong to more than one group. A group has an ID and a name. I was thinking to create 3 tables, a Person table and a Group table, then have a GroupMap table that would map the person.id to the group.id (which would both be primary and foreign keys). Here is what I have so far. I don't know if I am on the right track or doing this right.How can I make those foreign keys? Or should I set my tables up differently.

@Entity
public class Person implements Serializable {  
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;

   private String name;

}


@Entity
public class Group implements Serializable {
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;

   @Basic(optional = false)
   @Column(unique = true)
   private String name;
}

@Entity
public class GroupMap{
  @EmbeddedId
  private GroupPerson ids; 
}

@Embeddable
class GroupPerson implements Serializable {

  private Long person_id; //SHOULD BE FOREIGN KEY FROM person.id

  private Long group_id;  //SHOULD BE FOREIGN KEY FROM group.id

}

Upvotes: 0

Views: 223

Answers (1)

Affe
Affe

Reputation: 47994

There isn't really a reason GroupMap needs to be an Entity on its own at all unless you plan to add more properties to it.

@Entity
public class Person implements Serializable {  
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;

   private String name;

   @ManyToMany(mappedBy="persons")
   private List<Group> groups;

}


@Entity
public class Group implements Serializable {
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;

   @Basic(optional = false)
   @Column(unique = true)
   private String name;

  @ManyToMany()
  @JoinTable(name="group_map",
        joinColumns=@JoinColumn(name="GROUP_ID",referencedColumnName="ID"),
        inverseJoinColumns=@JoinColumn(name="PERSON_ID", referencedColumnName="ID"))
  private List<Person> persons;
}

All done!

Upvotes: 1

Related Questions