Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the JPA @SequenceGenerator annotation work

I am learning JPA and have confusion in the @SequenceGenerator annotation.

To my understanding, it automatically assigns a value to the numeric identity fields/properties of an entity.

Q1. Does this sequence generator make use of the database's increasing numeric value generating capability or generates the number on its own?

Q2. If JPA uses a database auto-increment feature, then will it work with datastores that don't have an auto-increment feature?

Q3. If JPA generates numeric value on his own, then how does the JPA implementation know which value to generate next? Does it consult with the database first to see what value was stored last in order to generate the value (last + 1)?


Q4. Please also shed some light on sequenceName and allocationSize properties of @SequenceGenerator annotation.

like image 527
Yatendra Avatar asked Apr 07 '10 19:04

Yatendra


2 Answers

sequenceName is the name of the sequence in the DB. This is how you specify a sequence that already exists in the DB. If you go this route, you have to specify the allocationSize which needs to be the same value that the DB sequence uses as its "auto increment".

Usage:

@GeneratedValue(generator="my_seq") @SequenceGenerator(name="my_seq",sequenceName="MY_SEQ", allocationSize=1) 

If you want, you can let it create a sequence for you. But to do this, you must use SchemaGeneration to have it created. To do this, use:

@GeneratedValue(strategy=GenerationType.SEQUENCE) 

Also, you can use the auto-generation, which will use a table to generate the IDs. You must also use SchemaGeneration at some point when using this feature, so the generator table can be created. To do this, use:

@GeneratedValue(strategy=GenerationType.AUTO) 
like image 57
Kevin Crowell Avatar answered Sep 21 '22 21:09

Kevin Crowell


I use this and it works right

@Id @GeneratedValue(generator = "SEC_ODON", strategy = GenerationType.SEQUENCE) @SequenceGenerator(name = "SEC_ODON", sequenceName = "SO.SEC_ODON",allocationSize=1) @Column(name="ID_ODON", unique=true, nullable=false, precision=10, scale=0) public Long getIdOdon() {     return this.idOdon; } 
like image 37
Edy Aguirre Avatar answered Sep 23 '22 21:09

Edy Aguirre