开发者

Extending an entity

开发者 https://www.devze.com 2022-12-23 11:58 出处:网络
I have class named AbstractEntity, which is annotated with @MappedSuperclass. Then I have a class named User (@Entity) which extends AbstractEntity. Both of these exist in a package named foo.bar.fram

I have class named AbstractEntity, which is annotated with @MappedSuperclass. Then I have a class named User (@Entity) which extends AbstractEntity. Both of these exist in a package named foo.bar.framework. When I use these two classes, everything works just fine. But now I've imported a jar containing these files to another project. I'd like to reuse the User class and expand it with a few additional fields. I thought that @Entity public class User extends foo.bar.framework.User would do the trick, but I found out that this implementation of the User only inherits the fields from AbstractEntity, but nothing from foo.bar.framework.User. The question is, how can I get my second User class to inherit all the fields from the first User entity class?

Both User class implementation have different table names defined with @Table(name = "name").

My classes look like this


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;

    ....
}

With the code above, EclipseLink will create a table named "myappuser" containing the fields "id", "consistencyVersion", "firstname", "lastname" and "email". The fields "usernam开发者_运维知识库e" and "password" are not created to the table - and that is the problem I'm having.


With JPA, the default inheritance strategy (i.e. when not specified) is SINGLE_TABLE: there is only one table per inheritance hierarchy and all fields are persisted in the table of the base class.

If you want to have a table for each class in the inheritance hierarchy and each table to contain columns for all inherited fields, you need to use a TABLE_PER_CLASS strategy.

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;

    ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消