How to persist abstract class with JPA

Asked

Viewed 1,304 times

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.

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

If I give persist() in the Car will save the Vehicle properties also?

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;
    }
}

1 answer

3


If you are looking for a mapping strategy with a single table (i.e., where there is a single table for Carro also containing the 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 (ie if you want to do polymorphic queries with Veiculo) it is also possible to annotate the abstract class with @Entity usually (see the section on inheritance in the official Java EE Tutorial). The superclass Veiculo should also receive the annotation Inheritance. With this setting it is possible to persist the class according to the best strategy for your case:

  • SINGLE_TABLE: Persists everything in a single table. This table contains columns for all attributes of all subclasses of Veiculo (in addition to the attributes defined in Veiculo). Attributes that belong to the other subclasses besides that persisted are null. A breakdown column is used to differentiate one class from the other.
  • JOINED: Table for Veiculo separate from the table for Carro. PK car is FK for Vehicle.
  • TABLE_PER_CLASS: Each subclass of Veiculo contains its own table. The attributes of Veiculo are copied to all subclasses. The difference between this strategy and @MappedSuperclass is that some providers JPA allow polymorphic queries using UNION.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.