我写了以下代码:
@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;
}
...
}
用户是一个人,用户可以拥有一组想要保留为联系人的“人”(Person-s)。所以,我在这里有继承(User derives Person)和聚合关系(User包含Person-s)。
就数据库表而言,我希望有3个表:
联系人表包含用户和个人表的外键。 实际上我只有以下两个表(人和用户): alt text http://picasaweb.google.com/yaneeve.shekel/ProgrammingRelated#5338298839877393922
我猜我的一些注释是不正确的......我做错了什么?
答案 0 :(得分: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