EJB,持久化期间的异常:“EntityManager必须在事务中访问”

时间:2016-06-09 09:07:30

标签: java transactions ejb

我收到此错误:“EntityManager必须在事务中访问”对我来说有什么奇怪的,因为我的bean带有注释标记:

@Stateless(name = "UserControllerSession")

我已经注入了EntityManager:

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

这是我的方法:

 @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;
    }

据我所知,EJB方法的默认值是Transactioanl.REQUIRED,因此应该创建defualt事务。另一个问题是,我可以在一次交易中持续2次吗?谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

我认为默认REQUIRED仅适用于您实际使用@TransactionAttribute注释的情况。尝试将其添加到您的方法(或类,如果您希望它作为所有方法的默认值)。