【问题标题】:Manage transaction with Hibernate使用 Hibernate 管理事务
【发布时间】:2017-10-30 05:15:09
【问题描述】:

我正在做一个项目,我使用 Hibernate+JPA 来管理我的数据库。

但是当我写我的服务时,我必须一直写这样的东西:

public String subscribe(String lastName, String firstName, String username, String borndate, String managerPwd) throws AuthenticationException, ExistingSubscriberException, SubscriberException, BadParametersException {
    try {
        this.authenticateMngr(managerPwd);

        this.em.getTransaction().begin();

        // Generate password and birthdate
        String password = UUID.randomUUID().toString();
        Calendar birthdate = CalendarManipulator.convertToCalendar(borndate);

        // Save player
        try {
            this.playerService.add(firstName, lastName, birthdate, username, password);
        } catch (PlayerAlreadyExistException e) {
            throw new ExistingSubscriberException();
        } catch (InvalidNameException | MinorPersonException | NullParameterException | InvalidPasswordException e) {
            throw new BadParametersException();
        } catch (Exception e) {
            this.unexeptedException(e);
        }

        this.em.getTransaction().commit();

        return password;
    }
    catch (Exception e) {
        this.em.getTransaction().rollback();
        throw e;
    }
}

这部分代码:

public void function {
    try {
        this.em.getTransaction().begin();

        // .......

        this.em.getTransaction().commit();

    }
    catch (Exception e) {
        this.em.getTransaction().rollback();
        throw e;
    }
}

我必须在每个服务上写...超过 50 :(

我没有使用 Spring(我知道它有一些解决方案),我在我的项目中单独使用 Hibernate + JPA。

是否存在不重复自己做同样事情的解决方案:)?

【问题讨论】:

  • 是的,如果你使用 Spring,它有一个名为 @Transactional 的注解,它会自动完成所有这些工作。看这里:docs.spring.io/spring/docs/current/javadoc-api/org/…
  • 如果您不使用 spring,您可以创建一个“Transactable”接口并将其传递给一个对象,该对象的唯一工作是捕获事务失败并回滚它们。有工厂就够了

标签: java spring hibernate maven jpa


【解决方案1】:

如果您使用的是纯 Java - 那么是的,您应该在每个服务中编写此样板代码。 但是,您可以使用 AOP,并为声明性事务划分创建自己的建议。

【讨论】:

  • 好的,我会看到的。谢谢:)
【解决方案2】:

您不需要一遍又一遍地编写它们。您可以使用 Spring 框架自动执行此操作。 Spring框架中有一个注解叫做@Transactionalhere

【讨论】:

  • 理解和实施 Spring 框架需要几个小时:s。实际上我会感兴趣,但我正在编写的代码是针对我必须在明天完成的学生项目^^'。
  • @graille 之所以不推荐你,是因为你给 Spring 贴了标签,说要学习 Spring。祝你好运
猜你喜欢
  • 1970-01-01
  • 2012-10-16
  • 2016-12-02
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多