My question concerns id field population of class object after persising. Example question below this class example
@Entity
class SomeEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
...
}
Let's say I want to persist new entity to repo like this:
SomeEntity entity = new SomeEntity(someArgs);
someEntityRepository.save(entity);
The question is - if I want to use id field, which in database is automatically generated, do I have to extract this entitiy once again:
SomeEntity foundEntity = someEntitiyRepository.findTheEntitySomehow(someargs);
System.out.println(foundEntity.getId());
or I can use it right out of the box?
// Copy code from above
SomeEntity entity = new SomeEntity(someArgs);
someEntityRepository.save(entity);
System.out.println(entity.getId());
CodePudding user response:
When you use repository save method Hibernate doesn't send a new record to the database until any flushing operation will be performed (like closing persistent context, or invoking JPQL statement).
To be sure that you will have an id, you have to invoke the flush manually. It can be called on any repository and all the persistent context will be flushed. Also saveAndFlush()
repository method can be used.
SomeEntity entity = new SomeEntity(someArgs);
someEntityRepository.saveAndFlush(entity);
System.out.println(entity.getId());
SomeEntity entity = new SomeEntity(someArgs);
someEntityRepository.save(entity);
someEntityRepository.flush();
System.out.println(entity.getId());
Keep in mind that just invoking save()
method will work too, if you don't have an open transaction (with @Transactional
annotation). Because save()
method will use own @Transactional
with opening and closing persistent context itself.
SomeEntity entity = new SomeEntity(someArgs);
someEntityRepository.save(entity);
System.out.println(entity.getId());
CodePudding user response:
SomeEntity entity = new SomeEntity(someArgs);
SomeEntity saved= someEntityRepository.save(entity);
Syster.out.println(saved.getId());
Whenever we are trying to use the Id, the state will change to persistence state and will get the Id value. We need to use the Id value from repository return object.