Difference Between @Id and @GeneratedValue in Spring Boot – Hibernate?

@Id and @GeneratedValue both are JPA Persistence annotations that are used to link a Java Variable as Primary to the DataBase Table(Used in Pers Layer). Apart from Linking these annotations also offer to do auto increment for the Primary Key.

@Id – Link the Database Primary Key to a Java Variable.
@GeneratedValue – To Enable Auto-Increment for the Primary Key.

Example :

@Entity
@Table(name="EMPLOYEE")
public class EmployeeEntity {
@Id
@GeneratedValue
private Long empId;

@Column(name="empName")
private String empName;
@Column(name="empExperience")
private int empExperience;
@Column(name="empJoinedDate")
private Date empJoinedDate;
}

On the above example, we have 4 Columns in the Table on which empId is defined as Primary Key, and this key holds the Unique for the Table and this will be auto-incremented through by the Default Sequence HIBERNATE_SEQUENCE.

So if you are not having the Sequence in the Table, When you execute the Operations it will through errors like

org.h2.jdbc.JdbcSQLSyntaxErrorException: Sequence "HIBERNATE_SEQUENCE" not found.
jpa annotations

Because we have defined the @GeneratedValue so the system is expecting the Sequence to be present at the Table.

So now the question is, Can you override the default SEQUENCE with User defined Sequence, Yes you can, to do that you have to Configure the @GeneratedValue as below.

@Id
@GeneratedValue(generator = "SEQ_EMPLOYEE")
private Long empId;

This means the empId is mapped with the user-defined Sequence, The default sequence is overridden, So when we do an operation it will check the sequence SEQ_EMPLOYEE than the default sequence HIBERNATE_SEQUENCE.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *