![]() |
面冷心慈的夕阳 · MyBatis零碎知识点_wx635b74c ...· 3 周前 · |
![]() |
面冷心慈的树叶 · Weston-keyboard not ...· 2 月前 · |
![]() |
细心的登山鞋 · How to Install Pip on ...· 8 月前 · |
![]() |
卖萌的烤地瓜 · 天生一对(曹杨): English ...· 8 月前 · |
![]() |
越狱的扁豆 · 肝细胞中RIPK3的表观遗传沉默通过抑制ML ...· 8 月前 · |
![]() |
眼睛小的西装 · [SPARK-25154] Support ...· 1 年前 · |
@GeneratedValue annotation, the name itself suggests that it will generate something. This annotation is generally used in conjunction with @Id annotation to automatically generate unique values for primary key columns within our database tables. When creating an entity class we have to specify a primary key for that entity. For marking the field property as a primary key of the entity we use @Id annotation. When we apply @GeneratedValue annotation to our primary key field or property. It will instruct hibernate to automatically generate a unique value for that field during the process of persisting the entity into the database. The @GeneratedValue annotation provides us with different strategies for the generation of primary keys which are as follows :
Example 1:
package
com.example.java_test_application;
// on the below line creating an entity class for the class
// of Employee.
@Entity
public
class
Employee {
// on the below line creating an employee id generated
// value with the strategy for generation type.
@GeneratedValue
(strategy = GenerationType.IDENTITY)
private
Long empId;
private
String employeeName;
private
String employeeQualification;
Explanation:
In the above example, we are considering an Employee entity. Inside this entity, we are marking empID with @Id annotation to indicate it as a primary key. The @GeneratedValue annotation with GenerationType Identity indicates that the primary key will be generated automatically by the database. The @GenaratedValue annotation simplifies generating unique primary key values and allows persistence providers to handle this task automatically, reducing boilerplate code needed for managing the primary keys in the database.
Example 2:
@Entity
public
class
Department {
// on the below line creating a variable for department
// id.
@GeneratedValue
(strategy = GenerationType.SEQUENCE)
private
Long departmentID;
// on the below line creating a variable for department
// name.
private
String departmentName;
Explanation:
In the above example, we are considering a Department entity. Inside this entity, we are marking departmentID with @Id annotation to indicate it as a primary key. The @GeneratedValue annotation with GenerationType SEQUENCE will generate primary key values which require the usage of the database sequence objects.
Last Updated : 21 Jun, 2023 Like Article