JPA inheritance and OneToMany relationship
I wrote 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 "Person-s" that he wants to keep as contacts. So I have both inheritance here (User gets Person) and aggregation relation (User contains Person-s).
In terms of database tables, I would expect 3 tables:
- man
- User
- contact
If the pins table contains foreign keys for the user and person tables. Actually I only have the following two tables (person and user): alt text http://picasaweb.google.com/yaneeve.shekel/ProgrammingRelated#5338298839877393922
I am assuming that some of my annotations are wrong ... What did I do wrong?
a source to share
While writing the question above, I found out that my relationship is a lot for many, since a person can be a contact of many users, while a user, of course, can have many contacts.
Here's the code to fix everything:
@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;
}
...
}
Now I am getting three tables that I expected: alt text http://picasaweb.google.com/yaneeve.shekel/ProgrammingRelated#5338298840732620802
- man
- User
- contact
a source to share