2009-05-21 84 views
0

我写了下面的代码:JPA继承和一对多关系

@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; 
    } 

... 

} 

用户在一个人与一个用户可以拥有一组“人”(人-S),它希望保持作为联系人。所以,我在这里的是继承(用户派生人)和聚合关系(用户包含人 - S)。

在数据库表方面我希望3个表:

  1. 用户
  2. 接触

凡接触表包含外键的用户和人表。 实际上我只有以下两个表(个人和用户): alt text http://picasaweb.google.com/yaneeve.shekel/ProgrammingRelated#5338298839877393922

我想,我的一些注释是不正确的......我做了什么错?

回答

1

在写上面的问题时,我发现我的关系是多对多的,因为一个人可能是许多用户的联系人,而用户当然可以有很多联系人。

这里是解决它的全部代码:

@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; 
    } 

... 

} 

我现在得到了三个表我的预期: alt text http://picasaweb.google.com/yaneeve.shekel/ProgrammingRelated#5338298840732620802

  1. 用户
  2. 接触