简体   繁体   中英

How to force commit transaction of EntityManager

I have the following case in a web app:

@Stateless
@LocalBean
public class AccountBean {
   
    @PersistenceContext(unitName = "foreign-context")
    private EntityManager fem;
    @PersistenceContext(unitName = "own-context")
    private EntityManager oem;

    public void doCreate() {
        Account account = createAccount();
        SubAccount subAccount = createSubAccount(account);
    }

    private Account createAccount() {
       Account account = new Account("This is a sample");
       oem.persist(account);
       oem.flush();
       return oem;
    }

    private SubAccount createSubAccount(Account account) {
       SubAccount subAccount = new SubAccount(account.getId()); // This field is only set after Account entity is persisted
       fem.persist(subAccount);
       fem.flush();
       return subAccount;
    }
} 

The problem as I see it is that account.getId() returns the default value 0 (as is int) causing SQL exception when attempting to save SubAccount due to table constraints. The ID field on account is supposed to be set after the Account is persisted however I suspect that due to the uncommitted transactions the result is not persisted, therefore the ID field is not updated in code. I have tested both of the methods individually and they seem to work fine but when combined the issue arises.

I have to use two separate EntityManager(s) due to business requirements having the model objects in different project dependencies each with it's own descriptor.

I have tried creating a new container managed transaction using @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) on createAccount() but to no avail.

The code runs on a Wildfly Server using Hibernate 5.2.4 if that's relevant. No other framework is used (except JPA)

How can I alleviate this issue?

Do not completely understand your code, method persist should return you object with id and you can use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM