我正在开发一个项目,并使用Hibernate + JPA来管理我的数据库。用Hibernate管理交易
但是,当我在写我的服务,我有写类似,所有的时间:
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:(
我不使用春天(我知道一些解决方案存在它),我在我的项目中单独使用Hibernate + JPA
是否存在解决方案来做同样的事情,而不重复自己:)?
泰
是的如果你使用Spring,它有一个名为@Transactional的注解,它将自动完成所有这些注释。查看这里:https://docs.spring.io/spring/docs /current/javadoc-api/org/springframework/transaction/annotation/Transactional.html –
如果您不使用spring,则可以创建一个“Transactable”接口并将其传递给一个对象,该对象的唯一工作是捕获事务失败并将其滚动背部。一个工厂应该足够了 – efekctive