When merging JPA entities using JpaTemplate in methods marked with @Async, the entity does not get an id. However, this works when merging it all in the same thread. (but taking way too long unfortunately).
For example:
...
@Autowired
private JpaTemplate jpaTemplate;
@Async
public Future<Foo> asyncSave(final Foo foo) {
return new AsyncResult<Foo>(save(foo));
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Foo save(final Foo foo) {
final Foo savedFoo = jpaTemplate.merge(foo);
return savedFoo; // <== savedFoo.getId() returns null !
}
...
Calling the method “asyncSave()” returns a Foo instance w/o id. In fact, I suspect the object returned is in the same state as before the merge. I’m seeing lots of SQL passing by on the console. The call to asyncSave() is coming from another repository object. And it really is a separate thread. So, what else can it be ?
Somebody ever had the same problem ?
Try to add @Transactional on method asyncSave.