简体   繁体   中英

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?

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;

    ...
}

like this. sample code.

@Entity(name = "project_document")
public class Document {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int idx;

    // ... setter, getter
}

...

@Id
@GeneratedValue(strategy=GenerationType.AUTO, generator="my_entity_seq_gen")
@SequenceGenerator(name="my_entity_seq_gen", sequenceName="MY_ENTITY_SEQ")
private long id;

enter link description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM