Johan
Johan

Reputation: 40618

How to use a custom SequenceGenerator for Hibernate in Spring for all entities?

I've implemented a custom SequenceGenerator that I want to use in all my entities for the "id". But rather than having to do something like this for each entity:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "XyzIdGenerator")
@GenericGenerator(name = "XyzIdGenerator",
        strategy = "com.mycompany.myapp.id.BigIntegerSequenceGenerator",
        parameters = {
            @Parameter(name = "sequence", value = "xyz_id_sequence")
        })
public BigInteger getId()
{
   return id;
}

is there a way to apply this SequenceGenerator to ALL entities by default using vanilla Hibernate/JPA or perhaps by using Spring?

Upvotes: 0

Views: 1659

Answers (1)

NewBee
NewBee

Reputation: 1469

Just move the code segment to a super class, add add @MappedSuperclass to it. But, in that case, all your entity will use the same seq generator

@MappedSuperclass
public class SeqIdable implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "XyzIdGenerator")
    @GenericGenerator(
    name = "XyzIdGenerator",
    strategy = "com.mycompany.myapp.id.BigIntegerSequenceGenerator",
    parameters = {
        @Parameter(name = "sequence", value = "xyz_id_sequence")
    })
    public BigInteger getId() {
       return id;
    }

}

Upvotes: 1

Related Questions