简体   繁体   中英

JPA not taking update into account within single Transaction

Within a transactional service method, I loop on querying a database to get the first 10 of entity A with a criteria.

I update each A entity from the list so that they don't match the criteria anymore, and call a flush() to make sure changes are made.

The second call to the query within the loop returns the exact same set of A entities.

Why isn't the flushed change on the entities taken into account?

I'm using JPA 2.0 with Hibernate 4.1.7. The same process with Hibernate only seems to be working. I've turned off the second level cache and the query cache, to no avail.

I'm using a rather plain configuration, JpaTransactionManager, Spring over JPA over Hibernate. Main method annotated with @Transactional.

The code would be something like this:

do {
    modelList = exportContributionDao.getContributionListToExport(10);
    for (M m : modelList) {
        //export m to a file
    m. (false);
    super.flush();
    }
} while (modelList.size() == 10);

With each iteration of the loop, the Dao method always return the same 10 results, JPA not taking into account the updated 'isToBeExported' attribute.

I'm not trying to solve a problem, rather I want to understand why JPA is not behaving as expected here. I expect this to be a 'classic' problem. No doubt it would be solved if the Transaction would be commited at each iteration.

ASAIK, the cache L1, ie the Session with Hibernate as the underlying JPA provider, should be up to date, and the second iteration query should take into account the updated Entities, even though the changes haven't been persisted yet. So my question is: why isn't it the case? Misconfiguration or know behavior?

Flush does not necessarily commit the changes on the database. What do you want to achieve? From what I understand you do s.th. like:

  1. Loop about entities
  2. Within the loop, change the entity
  3. Call 'flush' on the entity
  4. Read the entity back again
  5. You wonder why the data did not change on the database?

If this is correct, why do you re-read the changes and just don't work with the elements? After leaving the transaction, the changes will be automagically made persistent.

This should definitely be working.

This is a configuration problem on our part.

Apologies for the question, it was pretty hard to spot the reason on our part, but I hope the answer will at least be useful to some:

JPA definitely takes into account changes made on entities within a single transaction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM