我正在做一个项目,我使用 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。
是否存在一种解决方案可以做同样的事情而不重复我自己:)?
泰
最佳答案
如果您使用纯 Java - 那么是的,您应该在每个服务中编写此样板代码。 但是,您可以使用 AOP,并为声明性事务划分创建您自己的建议。
关于java - 使用 Hibernate 管理事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44250216/