0

I've been struggling for few hours with this one and could do with some help.

  1. A client sends an object that contains a list;
  2. One of the objects in the list has been modified on the client;
  3. In some cases I don't want that modified entity to be persisted to the database, I want to keep the original database values.

I have tried the following and various attempts to clear(), refresh() and flush() the session:

List<Integer> notToModifyIds = dao.getDoNotModifyIds(parentEntity.getId());
MyEntityFromList entityFromClient, entityFromDb;
for(Integer notToModifyId : notToModifyIds){
    ListIterator iterator = parentEntity.getEntities().listIterator();
    while(iterator.hasNext()){
        entityFromClient = (MyEntity) iterator.next();
        if(Objects.equals(entityFromClient.getId(), notToModifyId)){
            dao.evict(entityFromClient);
            entityFromDb = (MyEntity) dao.get(MyEntity.class, notToModifyId);
            iterator.remove(entityFromClient);
            iterator.add(entityFromDb);
        }
    }
}

However, no matter what I try I always get the values from the client persisted to the database. When I add a breakpoint after iterator.add() I can check that the database value has not been updated at that point, hence I know that if I could load the entity from the DB then I would have the value I want.

I'm feeling a little suppid!

Doahh
  • 590
  • 1
  • 8
  • 20

1 Answers1

1

I don't know if I got the whole scenario here. Are those modified "entitiesFromClient" attached to the Hibernate session? If they are, the changes were probably automatically flushed to the database before you "evicted" them. Setting a MANUAL flush mode would help you avoid the automatic behaviour. First of all, I would enable the Hibernate SQL logging to see more precisely what is happening. See Enable Hibernate logging.

Checking the database in another session (while stopped in the breakpoint) will not help if this code is running within a transaction. Even if the change was already flushed in the database you wouldn't see it until the transaction is commited.

Community
  • 1
  • 1
Douglas Gardim
  • 420
  • 1
  • 4
  • 11
  • I set `FlushMode.MANUAL` at the start and then call `dao.flush()` at the end. Several `select` statements get run and at the end an audit record is created and written to the database. The update of the `MyEntity` then occurs. I don't see anything unexpected at all. – Doahh Jan 22 '16 at 19:39
  • Hum... maybe it is cascade persisting your entity because it is still referenced in the parentEntity. Could you try to evict the parentEntity? My guess is because of this reported behavior: http://stackoverflow.com/questions/24756443/evicted-object-still-issues-updates-to-the-database-in-hibernate. – Douglas Gardim Jan 22 '16 at 20:25