My entity id is generated, and it was working fine when I use DAO instead of Spring data JPA.
@Id
@Column(name = TABLE_COLUM_NAME_ID)
@GeneratedValue
private int id;
Now I have starting to use Spring data JPA, and after I call repository.save(myboject)
, or repository.saveAndFlush(myobject)
, I call myobject.getId()
. But the id is never populated.
I searched my database and the object is in the database and the id is correct.
Does anyone know why the id is not set after i called save()
? I have no issue when I use entitymanager.save()
.
I finally figured it out. Even though the save method is void, you can set a variable to it.(?)
repository.saveAndFlush();
method:@GeneratedValue(strategy = GenerationType.AUTO)
) to the related field(id
):Try specifying strategy for
@GeneratedValue
likeTry this like
Then after call to
getId()
;This method returns the saved
id
Now you have your
id
.I believe this post answers your question:
Why to use returned instance after save() on Spring Data JPA Repository?
The
repository.save()
method actually returns a new object like JPAentityManager.merge()
and the returned object is the one that will have the ID set.