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:
@MappedSuperclass
@AutoProperty
public class MappedSuperClass implements Serializable {

 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 private long id; 
 
 private String s;

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

}
A class extends the mapped super class:
@Entity
@AutoProperty
public class InheritingMappedSuperClass extends MappedSuperClass {

 private String s2;

    // Setter, Getters, Constructors...

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

InheritingMappedSuperClass ce = new InheritingMappedSuperClass();
ce.setS("QQQ");
ce.setS2("DDD");

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

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

No comments:

Post a Comment