Wednesday, 22 August 2012

JPA Inheritance - Mapped Super Class

Mapped super classes are just like entities, but cannot be used like entities. They have ids and data to persist, but there is no corresponding table in the database. 

For example:
public class MappedSuperClass implements Serializable {

 private long id; 
 private String s;

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

A class extends the mapped super class:
public class InheritingMappedSuperClass extends MappedSuperClass {

 private String s2;

    // Setter, Getters, Constructors...

The following code:

InheritingMappedSuperClass ce = new InheritingMappedSuperClass();
InheritingMappedSuperClass retr = JPA.INSTANCE.get(
    InheritingMappedSuperClass.class, ce.getId());

System.out.println("Source == Retrieved: " + (ce==retr));
Generates the following output:
Source == Retrieved: false
InheritingMappedSuperClass{id: {1}, s: {QQQ}, s2: {DDD}}
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.