Java 使用Hibernate管理事务
我正在做一个项目,我使用Hibernate+JPA来管理我的数据库 但是当我写我的服务时,我必须一直写这样的东西:Java 使用Hibernate管理事务,java,spring,hibernate,maven,jpa,Java,Spring,Hibernate,Maven,Jpa,我正在做一个项目,我使用Hibernate+JPA来管理我的数据库 但是当我写我的服务时,我必须一直写这样的东西: public String subscribe(String lastName, String firstName, String username, String borndate, String managerPwd) throws AuthenticationException, ExistingSubscriberException, SubscriberException
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
是否存在一种解决方案,可以在不重复我自己的情况下做同样的事情:)
Ty如果您使用的是纯Java,那么是的,您应该在每个服务中编写此样板代码。
但是,您可以使用AOP,并为声明性事务划分创建自己的建议。您不需要反复编写它们。您可以使用Spring框架自动执行此操作。Spring框架中有一个名为
@Transactional
的注释是的,如果您使用Spring,它有一个名为@Transactional的注释,它将自动完成所有这些操作。请看这里:如果您不使用Spring,您可以创建一个“Transactiable”接口,并将其传递给一个对象,该对象唯一的工作就是捕获事务失败并回滚它们。有了工厂就足够了,我会看到的。谢谢:)理解并实施春季框架将花费我几个小时:s。事实上,我很感兴趣,但我写的代码是为了一个学生项目,我明天必须完成这个项目。^^。@graille我不推荐你的原因是因为你标记了Spring,并谈到了学习Spring。祝你好运