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:
public abstract class AbstractEntity implements Serializable {

    private long id;

    private String s;

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

A class extends the abstract class:
public class ConcreteEntity extends AbstractEntity {

    private String s2;

    // Setter, Getters, Constructors...

The following code:

ConcreteEntity ce = new ConcreteEntity();

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

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

No comments:

Post a comment