My requirement is to make hibernate fetch the latest value for PI already available in existing table and add new record by incrementing the the max PI value by one.
Below is my Entity class implementation
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
private String name;
}
Below is my class through which I enter value in User table
@PostMapping("/jpa/users")
public void addUser(@Valid @RequestBody User user)
{
User saved = userRepository.save(user);
}
My user table already has below values before I start my application
id name
1 sample_name_1
2 sample_name_2
Now when I start my application and try inserting new value in User table it should enter new record with PI as 3
Example: Below is JSON request body (Input)
{
"name": "sample_name_3"
}
It gives the below error
{
"timestamp": "2018-05-01T23:09:31.806+0000",
"status": 500,
"error": "Internal Server Error",
"message": "could not execute statement; SQL [n/a]; constraint [\"PRIMARY KEY ON PUBLIC.USER(ID)\"; SQL statement:\ninsert into user (name, id) values (?, ?) [23505-197]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
"path": "/jpa/users"
}
I understand it is having PrimaryIndex contraint error. It is trying to insert new record with PI as 1
If my user table is empty and when I insert couple of records, it adds new auto-incremented values.
So, I think Hibernate is not reading the latest value of id column from user table.
What annotation should I used to make hibernate read the latest value of id everytime before inserting new record.
PS: I've already tried below strategy and none of it works
GenerationType.TABLE
GenerationType.AUTO
GenerationType.SEQUENCE
GenerationType.IDENTITY