0

In the code snippet below, I am trying to persist two entities - Account and AccountDetails. I want this to be atomic. Meaning, both the Account and AccountDetails entites should be persisted in a single transaction. I am not able to achieve it.

Please note that the AccountDetails table refers the Account table with a foreign key (account.id).

If I try keeping them in the same transaction I run into a deadlock. Else, I need two different transactions with different sessions.

        Account instance = (Account) transientInstance;
        Set<AccountDetails> accountDetailses = instance.getAccountDetailses();
        AccountsHomeFactory factory = AccountsHomeFactory.getInstance();
        AccountDetailsHome accountDetailsDAO = (AccountDetailsHome) factory.getDAO("AccountDetails");

        transaction.begin();
        sessionFactory.getCurrentSession().persist(instance);

        transaction.commit();
                    // get new session ands start the transaction.
        transaction.begin();

        for (AccountDetails accountDetails : accountDetailses) {
            accountDetailsDAO.persist(accountDetails);
            log.debug("persist successful");
        }

        log.debug("transaction commit");
        transaction.commit();

Questions:

  1. How can I avoid the deadlock? Why does deadlock happen here? After all, logically, AccountDetails does not need a lock on Account to be persisted.
  • Though I have a work around where the sessions and transactions are taken care of by the individual data access objects, I cannot achieve the atomicity I am looking for. – Vikram Subramanian Apr 05 '12 at 08:47
  • Actually you can't use one session for more than one process. The strategy is one session for one process. You can use JPA implementation , I mean entitymanagerfactory and entitymanager. You can use entitymanager for many process. But I think with session it is not possible. – mbaydar Apr 05 '12 at 19:29
  • It does not make sense to create a transaction for a functional table and its details table. I would never want to separate the two operations. What if I want to make changes in multiple tables in a single transaction. Any way to do that? – Vikram Subramanian Apr 05 '12 at 23:42

1 Answers1

0

I think what you want to do is something possible. The solution is multiple transactions for one session. You can read this I hope it will help.

Community
  • 1
  • 1
mbaydar
  • 1,144
  • 1
  • 13
  • 18
  • Well you are right. Session can span across transactions. The transactions and sessions need to be centrally handled rather than leaving it the data objects or data layer entities. Thanks for your help. – Vikram Subramanian Apr 08 '12 at 10:46