Reputation: 1231
I'm working on an project, and I use Hibernate+JPA to manage my DB.
But when I'm writing my service, I have to write something like that ALL THE TIME :
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;
}
}
This part of code :
public void function {
try {
this.em.getTransaction().begin();
// .......
this.em.getTransaction().commit();
}
catch (Exception e) {
this.em.getTransaction().rollback();
throw e;
}
}
I have to write it on each sevices... more than 50 :(
I'm not using Spring (I know some solutions exist for it), I'm using Hibernate + JPA alone in my project.
Do exist a solution to do the same thing without repeating myself :) ?
Ty
Upvotes: 2
Views: 73
Reputation: 2194
You do not need to write them over and over again. You can use the Spring framework to do this automatically. There is an annotation in the Spring framework called @Transactional
here
Upvotes: 2
Reputation: 910
If you are using plain Java - then yes, you should write this boilerplate code in every service. However you could use AOP, and create your own advice for declarative transaction demarcation.
Upvotes: 2