1 Reply Latest reply on Jan 19, 2012 6:02 AM by sebastianovide

    How to do a Table lock with EJB3

    sappenin Novice

      In an EJB3 SLSB, how do I lock a database table so I can do a read, then a write in the same unit of work without having another calling thread do work in between? Please note that EntityManager.lock(...) will not work here because I need to lock the table BEFORE I create an entity.

      Here's the logic I'm looking for:

      1.) Lock the Database Table.
      2.) Read from the table to see if an object exists that meets my query requirements (the query use pk and non-pk data).
      3a.) If no data exists (that meets the requirements in #2), then create a new entry in the DB, and return this entry to the caller.


      3b.) If data *does* exists that matches the criteria set forth in #2 above, then return null to the caller. The caller will retry later in an attempt to get his object.

      4.) Release the table lock


      How do I do this with the EJB3 entityManager? I've annotated my SLSB function with @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW), but this doesn't prevent 2 callers from receiving "false" in #2 above, and hitting #3 at the same, thus returning a different object to both callers.