Reputation: 4779
I have written the following code:
@Entity
@Table(name="person")
@Inheritance(strategy=InheritanceType.JOINED)
public class Person {
private Long id;
protected String email;
private String firstName;
private String lastName;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
...
}
@Entity
@Table(name="users")
@ForeignKey(name="userPersonId")
public class User extends Person {
private String userName;
private String password;
private Date registrationDate;
private Set<? extends Person> contacts;
@OneToMany(targetEntity = com.blah.Person.class ,fetch = FetchType.LAZY, cascade=CascadeType.ALL)
@ForeignKey(name="contactId")
@JoinColumn(name="contactId")
public Set<? extends Person> getContacts() {
return contacts;
}
...
}
A User is a Person and a User can have a set of "people" (Person-s) that it wants to keep as contacts. So, what I have here is both inheritance (User derives Person) and an aggregation relation (User contains Person-s).
In terms of database tables I would expect 3 tables:
Where the contact table contains foreign keys to both the user and person tables. In actuality I only have the following two tables (person and user): alt text http://picasaweb.google.com/yaneeve.shekel/ProgrammingRelated#5338298839877393922
I guess that some of my annotations are incorrect... What have I done wrong?
Upvotes: 2
Views: 1783
Reputation: 4779
While writing the question above, I had figured out that my relation is many to many since a person may be a contact of many users while a user, of course, can have many contacts.
Here is the code to fix it all:
@Entity
@Table(name="users")
@ForeignKey(name="userPersonId")
public class User extends Person {
private String userName;
private String password;
private Date registrationDate;
private Set<? extends Person> contacts;
@ManyToMany(targetEntity = com.blah.Person.class, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@ForeignKey(name = "contactUserId", inverseName = "contactPersonId")
@JoinTable(name = "contact", joinColumns = {@JoinColumn(name = "userId")}, inverseJoinColumns = {@JoinColumn(name = "personId")})
public Set<? extends Person> getContacts() {
return contacts;
}
...
}
I now get the three tables I expected: alt text http://picasaweb.google.com/yaneeve.shekel/ProgrammingRelated#5338298840732620802
Upvotes: 2