Krismorte
Krismorte

Reputation: 632

How to work @Inheritance plus GenerationType.SEQUENCE

I'm trying to create a way to model my future aplications using an AbstractEntity My problem now is the Sequence type for Postgres

In my abstract class I don't now how generate one sequence per entity class

It is possible?

Abstract

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Abstract {

    @Id
    @GeneratedValue(generator="seq_Broker",strategy=GenerationType.SEQUENCE)
    @SequenceGenerator(name="seq_Broker",sequenceName="seq_Broker")
    private Long id;

}

EntityModel

@Entity
@Table(name = "tb_EntityModel")
public class EntityModel extends Abstract{

    private String value;
    private String value2;

    public EntityModel(String value, String value2) {
        this.value = value;
        this.value2 = value2;
    }
}

Upvotes: 1

Views: 984

Answers (1)

Tobias Liefke
Tobias Liefke

Reputation: 9022

It is not possible with an @Entity superclass for any inheritance types, as the master table (the table for Abstract) will always contain the used ids - and it is obvious that you can only use one sequence for that, as otherwise you would have a problem with uniqueness.

But you can define @MappedSuperclass for Abstract:

@MappedSuperclass
public abstract class Abstract {
    public static final String SEQUENCE_GENERATOR = "seq";

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE_GENERATOR)
    private Long id;
}

@Entity
@Table(name = "tb_EntityModel")
@SequenceGenerator(name = Abstract.SEQUENCE_GENERATOR, sequenceName = "tb_entity_sequence")
public class EntityModel extends Abstract { 
    ... 
}

Upvotes: 2

Related Questions