1

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

1 Answer 1

1

The generation type you want to use is GenerationType.IDENTITY, however you need to

  1. use a database which supports identity columns, and
  2. correctly define your primary key column to be an identity column.

So for example in PostgreSQL, you would define your primary key column like this:

CREATE TABLE mytable (
  id serial primary key,
  ...

Definitive information about this is available in the JPA specification under section 11.1.20 GeneratedValue Annotation.

Sign up to request clarification or add additional context in comments.

1 Comment

I was using in-memory database H2. I will try it in mysql and update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.