3 Replies Latest reply on Mar 8, 2007 2:06 PM by Chuck Adams

    manual flushing and state from database

    francesco milesi Newbie

      hi everybody,

      I have a conversation component derived from EntityHome with manual flush mode. Before flushing changes for the associated entity to the db I would like to re-read its status field from db and stop saving the changes if it has a specific value that was posted by a concurrent user. The problem is that, if I refresh the entity to get the current status from db I obviously lose the changes submitted from the form and, if I use the entity manager to get another instance of the same record using a query and getSingleResult(), I get the same instance I obtain calling getInstance(), and such instance has the old value of the status field.
      How can I do that?

      Thanks in advance

      ciao Francesco

        • 1. Re: manual flushing and state from database
          Christian Bauer Master

          Not sure this is a good idea, because you _want_ to break repeatable read isolation of your conversation/transaction. But you can with a scalar query, a query that doesn't return entity instances (which would hit the persistence context cache): select e.statusProperty from MyEntity e

          This goes straight to the database and returns this value, the only cache that could be between you and the data is the Hibernate second-level query cache (which isn't enabled by default).

          • 2. Re: manual flushing and state from database
            Christian Bauer Master

            Btw, this is usually solved with versioning and automatic optimistic locking: You'd get a StaleObjectState (or the equivalent EJB3 exception) when you try to save and someone else modified the same row.

            • 3. Re: manual flushing and state from database
              Chuck Adams Novice

              Versioning and optimistic locking is also immune to the inevitable race condition of checking for changes before a commit. It does throw an exception though, which makes recovery like offering a "merge" screen somewhat complicated.

              Sometimes you still might want to peek outside the current transaction, like if you wanted to poll for changes during an edit session and show a warning. A query in a different entitymanager (like one you get from @PersistenceContext or from JNDI) ought to do the trick, no?