扩展实体

时间:2010-03-21 19:45:26

标签: java jpa eclipselink

我有一个名为AbstractEntity的类,它使用@MappedSuperclass注释。然后我有一个名为User(@Entity)的类,它扩展了AbstractEntity。这两个都存在于名为foo.bar.framework的包中。当我使用这两个类时,一切正常。但是现在我已经将包含这些文件的jar导入到另一个项目中。我想重用User类并使用一些额外的字段进行扩展。我认为@Entity public class User extends foo.bar.framework.User可以解决问题,但我发现User的这个实现只继承了AbstractEntity中的字段,但没有来自foo.bar.framework.User。问题是,如何让我的第二个User类继承第一个User实体类的所有字段?

两个User类实现都有不同的表名,用@Table(name =“name”)定义。

我的课程看起来像这样


package foo.bar.framework;

@MappedSuperclass
abstract public class AbstractEntity {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
    protected Long id;

    @Column(nullable = false)
    @Version
    protected Long consistencyVersion;

    ...
}


package foo.bar.framework;

@Entity
@Table(name = "foouser")
public class User extends AbstractEntity {

    protected String username;

    protected String password;

    ....
}


package some.application;

@Entity
@Table(name = "myappuser")
public class User extends foo.bar.framework.User {

    protected String firstname;

    protected String lastname;

    protected String email;

    ....
}

使用上面的代码,EclipseLink将创建一个名为“myappuser”的表,其中包含字段“id”,“consistencyVersion”,“firstname”,“lastname”和“email”。字段“username”和“password”不会创建到表中 - 这就是我遇到的问题。

1 个答案:

答案 0 :(得分:5)

使用JPA,默认继承策略(即未指定时)为SINGLE_TABLE:每个继承层次结构只有一个表,所有字段都保存在基类的表中。

如果要为继承层次结构中的每个类创建一个表,并且每个表包含所有继承字段的列,则需要使用TABLE_PER_CLASS策略。

package foo.bar.framework;

@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
abstract public class AbstractEntity {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
    protected Long id;

    @Column(nullable = false)
    @Version
    protected Long consistencyVersion;

    ...
}