How to persist abstract class with JPA

4

I know JPA and I have other tables already implemented and working.

I would like to know how to persist the classes below, since one is an abstract class and the other is "extending" it.

Should I put annotations and properties as if they were classes 1 to N?

If I give persist() to the car will it save the properties of the vehicle as well?

public abstract class Veiculo {
    private int idVeiculo;
    public int getIdVeiculo() {
        return idVeiculo;
    }
    public void setIdVeiculo(int idVeiculo) {
        this.idVeiculo = idVeiculo;
    }
}

-

public class Carro extends Veiculo {
    private String marca;
    public String getMarca() {
        return marca;
    }
    public void setMarca(String marca) {
        this.marca = marca;
    }
}
    
asked by anonymous 08.04.2015 / 21:09

1 answer

2

If you are looking for a mapping strategy with a single table (that is, where there is only one table for Carro , also containing columns defined in Veiculo ) all you have to do is write down Veiculo with @MappedSuperclass .

If you really want to consider the Vehicle class as an entity (that is, if you want to make polymorphic queries with Veiculo ) you can also annotate the abstract class with @Entity normally (see section on inheritance in the official Java EE Tutorial). The Veiculo superclass should also receive the Inheritance annotation. With this configuration you can persist the class according to the best strategy for your case:

  • SINGLE_TABLE : Persist all in a single table. This table contains columns for all attributes of all subclasses of Veiculo (in addition to the attributes defined in Veiculo ). Columns that belong to the other subclasses other than the one persisted are null. A discriminator column is used to differentiate one type from another.
  • JOINED : Table for Veiculo separated from table for Carro . % of car% is PK to Vehicle.
  • FK : Each subclass of TABLE_PER_CLASS contains its own table. The attributes of Veiculo are copied to all subclasses. The difference between this strategy and Veiculo is that some providers JPA allow polymorphic queries using @MappedSuperclass .
08.04.2015 / 22:15