Search code examples
javatransactionsejb

EJB, exception during persist: "EntityManager must be access within a transaction"


I received this error: "EntityManager must be access within a transaction" what is strange for me because my bean is mark with annotation:

@Stateless(name = "UserControllerSession")

I have injected EntityManager like this:

@PersistenceContext(unitName = "app")
    private EntityManager em;

and this is my method:

 @Override
    @PermitAll
    public String updateBlockedAndDeactivationReasonForIds(String userPk, String iban, List<String> associatedIds) {
        UserLocal user = em.find(UserLocal.class, Long.valueOf(userPk));
        if (user == null) {
            return ("User with id: " + userPk + " does not exist ! \n");
        }

        user.setBlocked(true);
        user.setActive(false);
        user.setDeactivationReason(DeactivationReason.DEACTIVATION_MULTIPLY_IBAN_REASON);
        user.setDeactivationDate(new Date());

        StringBuilder message = new StringBuilder();
        message.append(" IBAN " + iban + " is linked to multiple accounts: ");
        for (String id : associatedIds) {
            message.append(id + " ");
        }

        ContactJournalEntryBean cjb = new ContactJournalEntryBean("USER", user.getLogin(), new Date(), "Internet",
                message.toString());
        em.persist(user);
        em.persist(cjb);

        return "SUCCESS operation for user with id: " + userPk;
    }

As far I know default value for EJB method is Transactioanl.REQUIRED so by defualt transaction should be created. Another question is can I have 2 persists in one transaction ? Thanks for any help


Solution

  • I think the default REQUIRED only applies if you actually use the @TransactionAttribute annotation. Try adding it to your method (or class if you want it as default on all methods).