开发者

Mapping compound foreign key in hibernate

开发者 https://www.devze.com 2023-03-26 07:30 出处:网络
I asked a question here on how to design a database schema. In summary I have an addressbook that can contain contacts and groups.Groups can also contain contacts, but only contacts which are in the

I asked a question here on how to design a database schema.

In summary I have an addressbook that can contain contacts and groups. Groups can also contain contacts, but only contacts which are in the same addressbook as them.

Addressbook

Addressbook id

Contact

id

Addressbook id

Group

id

Group id

Group To Contact

id

Addressbook id

Contact id

Group id

B开发者_C百科y adding addressbook id to the many to many relationship table, I can enforce that the addressbooks match. I am however relatively new to hibernate, so:

  @Entity
  @Table(name = "Contact")
  public class Contact 
  {
    Addressbook addressbook;

    //----bidirectional association
    private List groups = new ArrayList();
    //----
  }

  @Entity
  @Table(name = "Group")
  public class Group 
  {
    Addressbook addressbook;
    //----bidirectional association
    private List contacts = new ArrayList();
    //----
  }

So at a starting point, I would have the above two tables, and I would need the collections to be controlled by hibernate in a way which would enforce that the addressbook id's match when adding, or modifying objects within the collection.


You need to specify type of elements in collection and add annotation ManyToMany

  @Entity
  @Table(name = "Contact")
  public class Contact 
  {

    @Id
    @GeneratedValue(GenerationType=AUTO)
    private Integer contact_id;

    Addressbook addressbook;

    //----bidirectional association
    //@ManyToMany
    //private List<Group> groups = new ArrayList<Group>();
    //----
  }

And I think, there is no need to add collection groups to Contact. You can select groups by contact id from Groups table. Also, you need to add id's to each table.

  @Entity
  @Table(name = "Group")
  public class Group 
  {
    @Id
    @GeneratedValue(GenerationType=AUTO)
    private Integer group_id;

    Addressbook addressbook;
    //----bidirectional association
    @ManyToMany
    private List<Contact> contacts = new ArrayList<Contact>();
    //----
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号