Question

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.
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top