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:
@AutoProperty
public class NonEntitySuperClass {

 private String s;

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

}
A class extends this non-entity class:
@Entity
@AutoProperty
public class InheritingNonEntitySuperClass
    extends NonEntitySuperClass
        implements Serializable {
 
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;
 
    private String s2;

    // Setter, Getters, Constructors...

}
The following code:
JPA.INSTANCE.clear();

InheritingNonEntitySuperClass insc
    = new InheritingNonEntitySuperClass();
insc.setS("P1P");
insc.setS2("AZ3");
  
JPA.INSTANCE.save(insc);
JPA.INSTANCE.clear();
  
InheritingNonEntitySuperClass retr = JPA.INSTANCE.get(
    InheritingNonEntitySuperClass.class, insc.getId());

System.out.println("Source == Retrieved: " + (insc==retr));
System.out.println(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.