Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data jpa save can not get id

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().

like image 259
Grey Avatar asked May 03 '13 03:05

Grey


People also ask

Can we create JPA entity without id?

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.

How can we avoid duplicate records in JPA?

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.

What does JPA save return?

JPA's persist method returns void and Hibernate's save method returns the primary key of the entity.

What is id in CrudRepository?

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.


1 Answers

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.

like image 80
wrschneider Avatar answered Sep 19 '22 17:09

wrschneider