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 idContact
id Addressbook idGroup
id Group idGroup To Contact
id Addressbook id Contact id Group idB开发者_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>();
//----
}
精彩评论