Spring data jpa save can not get id
- You should use the
repository.saveAndFlush();
method:
MyObject savedObject= repository.saveAndFlush(newObject);
- In the Entity object description, you should add the following attribute(
@GeneratedValue(strategy = GenerationType.AUTO)
) to the related field(id
):
@Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.AUTO) public long getId() { return 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 JPA entityManager.merge()
and the returned object is the one that will have the ID set.
Try this like
myboject = repository.save(myboject);
repository.flush();
Then after call to getId()
;
This method returns the saved id
myobject = repository.saveAndFlush(myobject);
Now you have your id
.