1

I want that the primary key "puid" gets automatically generated. However I the puid still is always 0. I tried different GeneratedValue variants (Sequence, Identity and Auto) but the result is the same.

This is my code:

@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long puid; 

Does anyone have an idea how to fix that?

2
  • 1
    It is recommended to use nullable types such as Long for IDs. Commented Jul 23, 2021 at 14:45
  • Is the entity you are checking the value on already persisted? The auto generation of the ID is handled by the database, so as long as no saving to the actual DB took place the value will still be the default. Commented Jul 23, 2021 at 14:48

2 Answers 2

4
  1. puid has default value 0, when an object is just created.
  2. Hibernate thinks that you set puid value manually, Hibernate doesn't change it. Just change long to Long to have null initial value.
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long puid; 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the solution only problem is know when I am using that I get a unique constraint error
@user15980267 Better to create a new question with error stack trace and example of the entity.
2

Use Wrapper object which supports null values as well.

Change long to Long

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.