【问题标题】:jpa inheritance and a OneToMany Relationjpa 继承和 OneToMany 关系
【发布时间】:2010-10-27 23:20:35
【问题描述】:

我写了以下代码:

@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),它想保持联系。因此,我在这里拥有的是继承(用户派生 Person)和聚合关系(用户包含 Person-s)。

就数据库表而言,我希望有 3 个表:

  1. 用户
  2. 联系方式

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

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

【问题讨论】:

    标签: java inheritance jpa aggregation


    【解决方案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. 联系方式

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      • 2012-08-20
      • 2014-07-30
      相关资源
      最近更新 更多