Wednesday, 22 August 2012

JPA Inheritance - Non Entity Super Class

An entity can inherit of a non-entity super class. The consequence is that the non-entity class data is not persisted.

For example:
public class NonEntitySuperClass {

 private String s;

    // Setter, Getters, Constructors, Pojomatic...

A class extends this non-entity class:
public class InheritingNonEntitySuperClass
    extends NonEntitySuperClass
        implements Serializable {
    private long id;
    private String s2;

    // Setter, Getters, Constructors...

The following code:

InheritingNonEntitySuperClass insc
    = new InheritingNonEntitySuperClass();
InheritingNonEntitySuperClass retr = JPA.INSTANCE.get(
    InheritingNonEntitySuperClass.class, insc.getId());

System.out.println("Source == Retrieved: " + (insc==retr));
Generates the following output:
Source == Retrieved: false
InheritingNonEntitySuperClass{s: {null}, id: {1}, s2: {AZ3}}
Notice that the s value is null, instead of P1P.

The above example is available from Github in the JPA directory. It relies on Pojomatic too. Some errors messages will be displayed because of a known and harmless issue.

No comments:

Post a comment