javajpasequence-generators

JPA SequenceGenerator: All generators in single table


I'm using 3 different JPA SequenceGenerators. Everyone creates its own table in datasource with given name:

@SequenceGenerator(name = "a_seq", sequenceName = "A_SEQ")
@SequenceGenerator(name = "b_seq", sequenceName = "B_SEQ")
@SequenceGenerator(name = "c_seq", sequenceName = "C_SEQ")

Is there a way to combine them all in one table, let's say SEQUENCE table, and every generator is one row in this table?


Solution

  • You need to use a Table generator (which stores the id value in a specified table) rather than Sequence generator (which uses native SQL sequences). This simplified example below should give you the idea, but you can control the schema for the table by specifying more attributes on the @TableGenerator annotation.

    @TableGenerator(name="MyTableGen", table="SEQUENCES", pkColumnValue="MyClass")
    @Entity
    public class MyEntity
    {
        @Id
        @GeneratedValue(strategy=GenerationType.TABLE, generator="MyTableGen")
        private long myId;
    
        ...
    }