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()
.
If your object does not have an id, but its' table does, this is fine. Make the object an Embeddable object, embeddable objects do not have ids. You will need a Entity that contains this Embeddable to persist and query it.
To avoid having JPA persist the objects automatically, drop the cascade and use persist to manually add the objects to the context immediately after creation. Since a persistence context is basically a tricked-out WeakHashMap attached to a database, these approaches are pretty similar when it comes down to it.
JPA's persist method returns void and Hibernate's save method returns the primary key of the entity.
CrudRepository. CrudRepository interface provides generic CRUD operations on a repository for a specific type. Its findById method retrieves an entity by its id. The return value is Optional<T> . Optional<T> is a container object which may or may not contain a non-null value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With