【问题标题】:EJB, exception during persist: "EntityManager must be access within a transaction"EJB,持久化期间的异常:“EntityManager 必须在事务中访问”
【发布时间】:2016-06-09 09:07:29
【问题描述】:

我收到此错误:“EntityManager must be access within a transaction”这对我来说很奇怪,因为我的 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,因此应该创建默认事务。另一个问题是我可以在一个事务中保留 2 个吗?感谢您的帮助

【问题讨论】:

  • 您可以拥有任意数量的persist
  • 为什么需要em.persist(user);?因为 find() 方法会返回一个UserLocal 的实例,并且这个实例是托管的。因此,当方法退出时,更改将被保存。

标签: java transactions ejb


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多