Wednesday, 22 August 2012

JPA Inheritance - Abstract Entity

An abstract class can be made a JPA entity. The only difference is that such classes cannot be instantiated.

For example:
@Entity
@AutoProperty
public abstract class AbstractEntity implements Serializable {

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

    private String s;

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

}
A class extends the abstract class:
@Entity
@AutoProperty
public class ConcreteEntity extends AbstractEntity {

    private String s2;

    // Setter, Getters, Constructors...

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

ConcreteEntity ce = new ConcreteEntity();
ce.setS("AAA");
ce.setS2("BBB");

JPA.INSTANCE.save(ce);
JPA.INSTANCE.clear();

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

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