I encountered the following problem and have been pulling my hair for the past week because I can't figure out what is wrong.
Essentially, I want to receive data via a REST request to persist an entity to my postgres DB, and immediately respond with the created entity and the resource path where it can be requested in the future.
My unit test for both read and write operation work flawlessly, but if I start a REST-test for the sequence above, the test can't find the persisted data.
My repo class is annotated with @Transactional, @Stateless and @TransactionAttribute(REQUIRES_NEW)
I persist and return the entities id with the default
Entitymanager em;
em.persist(entity);
em.refresh(entity);
return entity.getId();
and read back with
em.createQuery("select distinct e from EntityClass e where e.id = :id", EntityClass.class)
.setParameter("id", id)
.getResultStream()
.findAny();
If the write method returns for example the ID 7 for my entity, the read back yields no result for ID = 7, even though the ID is generated by a DB sequence.
Every manual test I do with the deployed application does work without a problem, though I want these failing test to return to green.
I encountered the following problem and have been pulling my hair for the past week because I can't figure out what is wrong.
Essentially, I want to receive data via a REST request to persist an entity to my postgres DB, and immediately respond with the created entity and the resource path where it can be requested in the future.
My unit test for both read and write operation work flawlessly, but if I start a REST-test for the sequence above, the test can't find the persisted data.
My repo class is annotated with @Transactional, @Stateless and @TransactionAttribute(REQUIRES_NEW)
I persist and return the entities id with the default
Entitymanager em;
em.persist(entity);
em.refresh(entity);
return entity.getId();
and read back with
em.createQuery("select distinct e from EntityClass e where e.id = :id", EntityClass.class)
.setParameter("id", id)
.getResultStream()
.findAny();
If the write method returns for example the ID 7 for my entity, the read back yields no result for ID = 7, even though the ID is generated by a DB sequence.
Every manual test I do with the deployed application does work without a problem, though I want these failing test to return to green.
Share Improve this question edited 3 hours ago DarthDonut asked 3 hours ago DarthDonutDarthDonut 1236 bronze badges1 Answer
Reset to default 0I'm not too sure. But I think if the persistence context lifecycle has not ended, changes made to the managed entities in the persistence context are not immediately reflected in the database. You can invoke em.flush() to make force synchronization.
em.persist(entity);
em.flush(); // Ensures the entity is saved to DB
em.refresh(entity); // Reloads the entity with DB state
return entity.getId();