Question

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:

  1. person
  2. user
  3. contact

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?

Was it helpful?

Solution

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

  1. person
  2. user
  3. contact
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top