☰ See All Chapters |
JPA @GeneratedValue Annotation
@GeneratedValue annotation is used to allow the persistence implementation to assign a unique value to your identity fields automatically. @GeneratedValue is used only to get the generated value, it will not generate the value. It is used to specify how to get the value for ID field. @GeneratedValue must be annotated along with Id annotation.
The two arguments strategy and generator are used to define how the value is obtained.
strategy
This is used to specify how to auto-generate the field value. There are four possible values for the strategy element on the GeneratedValue annotation: IDENTITY, AUTO, TABLE and SEQUENCE. These four values are available in the enum, GeneratorType.
GeneratorType.AUTO: The default. Assign the field a generated value, leaving the details to the JPA vendor. Tells JPA to pick the strategy that is preferred by the used database platform. The preferred strategies are IDENTITY for MySQL, SQLite and MsSQL and SEQUENCE for Oracle and PostgreSQL. This strategy provides full portability.
GenerationType.IDENTITY: The database will assign an identity value on insert. Tells Doctrine to use special identity columns in the database that generate a value on insertion of a row. This strategy does currently not provide full portability and is supported by the following platforms:
MySQL/SQLite => AUTO_INCREMENT
MSSQL => IDENTITY
PostgreSQL => SERIAL
GenerationType.SEQUENCE: Use a datastore sequence to generate a field value. Tells JPA to use a database sequence for ID generation. This strategy does currently not provide full portability. Sequences are supported by Oracle and PostgreSql. When this value is used then generator filed is mandatory to specify the generator.
GenerationType.TABLE: Use a sequence table to generate a field value. Tells JPA to use a separate table for ID generation. This strategy provides full portability. When this value is used then generator filed is mandatory to specify the generator.
generator
This is used to specify the name of the named generator. Named generators are defined using SequenceGenerator, TableGenerator. When GenerationType.SEQUENCE and GenerationType.TABLE are used as a strategy then we must specify the generators. Value for this generator field should be the name of SequenceGenerator, TableGenerator
JPA @SequenceGenerator Annotation
Most databases allow you to create native sequences. These are database structures that generate sequential values. The @SequenceGenerator annotation is used to represent a named database sequence. This annotation can be kept on class level, member level. @SequenceGenerator annotation has the following properties:
String name: The generator name. This property is mandatory.
String sequenceName: The name of the database sequence. If you do not specify the database sequence, your vendor will choose an appropriate default.
int initialValue: The initial sequence value.
int allocationSize: The number of values to allocate in memory for each trip to the database. Allocating values in memory allows the JPA runtime to avoid accessing the database for every sequence request. This number also specifies the amount that the sequence value is incremented each time the sequence is accessed. Defaults to 50.
String schema: The sequence's schema. If you do not name a schema, JPA uses the default schema for the database connection.
JPA @TableGenerator Annotation
@TableGenerator annotation refers to a database table which is used to store increasing sequence values for one or more entities. This annotation can be kept on class level, member level. @TableGenerator has the following properties:
String name: The generator name. This property is mandatory.
String table: The name of the generator table. If left unspecified, database vendor will choose a default table.
String schema: The named table's schema.
String catalog: The named table's catalog.
String pkColumnName: The name of the primary key column in the generator table. If unspecified, your implementation will choose a default.
String valueColumnName: The name of the column that holds the sequence value. If unspecified, your implementation will choose a default.
String pkColumnValue: The primary key column value of the row in the generator table holding this sequence value. You can use the same generator table for multiple logical sequences by supplying different pkColumnValue s. If you do not specify a value, the implementation will supply a default.
int initialValue: The value of the generator's first issued number.
int allocationSize: The number of values to allocate in memory for each trip to the database. Allocating values in memory allows the JPA runtime to avoid accessing the database for every sequence request. This number
Difference between GeneratedValue and SequenceGenerator/TableGenerator
GeneratedValue is used only to get the generated value. The two arguments strategy and generator are used to define how the value is obtained. We can define to use the database sequence or any database value from table which is used to store increasing sequence values. But to specify to use database sequence or table value, we specify the named generators to generator argument.
SequenseGenerator/TableGenerator is used to define named generators, to map a user defined sequence generator with your JPA session. This is used to give a name to database sequence or database value of table or any kind of generators. This name can be now referred by the generator argument of GeneratedValue.
@Entity
@Table(name = "STUDENT")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
}
----------------------------
@Entity
@Table(name = "STUDENT")
@ SequenceGenerator (sequenceName = databaseSequenceNameInDB, name = nameForTheGenerator)
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = nameForTheGenerator )
private int id;
}
----------------------------
@Entity
@Table(name = "STUDENT")
@ TableGenerator (sequenceName = nameOfGeneratorTableInDB, name = nameForTheGenerator)
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = nameForTheGenerator )
private int id;
}
Now let see example for GeneratedValue, SequenceGenerator, TableGenerator annotation.
JPA GeneratedValue, SequenceGenerator, TableGenerator Annotation Example
Database script for Mysql
CREATE TABLE STUDENT ( ID INT AUTO_INCREMENT PRIMARY KEY, FIRSTNAME VARCHAR(20) DEFAULT NULL, LASTNAME VARCHAR(20) DEFAULT NULL ); |
Student.java
package com.java4coding;
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table;
@Entity @Table(name = "STUDENT") public class Student {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) // We can also use GenerationType.AUTO // @GeneratedValue(strategy=GenerationType.AUTO) private int id;
private String firstName;
private String lastName;
public int getId() { return id; }
public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; } } |
Test.java
package com.java4coding;
import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence;
public class Test { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("StudentPU"); EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Student student = new Student(); student.setFirstName("Manu"); student.setLastName("Manjunatha");
em.persist(student); em.getTransaction().commit();
} } |
Output:
We have executed the program four times and below is the corresponding output:
All Chapters