views:

81

answers:

1

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 "username" and "password" are not created to the table - and that is the problem I'm having.

+1  A: 

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;

    ...
}
Pascal Thivent
This is correct, however this didn't solve my problem totally. It seems that I cannot have two entities with the same name (even if they were in different packages). This meant that the framework's User table didn't get created, actually, EclipseLink seemed to ignore it totally. To fix my problem, I had to rename the other User entity class AND do the changes you suggested.
Kim L