Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Add lock(bean) method as convenience for DB pessimistic locking #2362

Closed
rbygrave opened this issue Sep 9, 2021 · 0 comments
Closed
Assignees
Milestone

Comments

@rbygrave
Copy link
Member

rbygrave commented Sep 9, 2021

This will effective load or refresh the bean and obtain a database row lock using select for update

   try (Transaction transaction = DB.beginTransaction()) {

     // fetch something that relates to what we want to lock
      Order order = DB.find(Order.class, o0.getId());

      // we have a reference bean (only has id) but could be partial or fully loaded
      Customer customer = order.getCustomer();

      // load and obtain database row lock
      // load the customer bean using select for update
      // bean is now loaded and database row lock held until commit
      database.lock(customer); 
 
     ...
      transaction.commit();
    }

More fully explained with asserts

    try (Transaction transaction = DB.beginTransaction()) {

      LoggedSql.start();
      Order order = DB.find(Order.class, o0.getId());
      assert order != null;

      Customer customer = order.getCustomer();
      assertEquals(customerId, customer.getId());
      assertTrue(DB.beanState(customer).isReference());

      DB.lock(customer); // load the customer bean using select for update
      // bean is now loaded and database row lock held until commit
      assertFalse(DB.beanState(customer).isReference());

      assertThat(customer.getName()).isNotNull();

      List<String> sql = LoggedSql.stop();
      assertThat(sql).hasSize(2);
      assertThat(sql.get(0)).contains("from o_order");
      assertThat(sql.get(1)).contains("from o_customer t0 where t0.id = ?   for update");

      transaction.commit();
    }
@rbygrave rbygrave self-assigned this Sep 9, 2021
@rbygrave rbygrave changed the title ENH: Add lock(bean) method as convienence for DB pessimistic locking ENH: Add lock(bean) method as convenience for DB pessimistic locking Sep 9, 2021
@rbygrave rbygrave added this to the 12.11.4 milestone Sep 9, 2021
@rbygrave rbygrave closed this as completed Sep 9, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant