I’m trying to make my DAO work this way:
public void incrementNumber(long id) throws Exception{
Session session = factory.openSession();
Number n = (Number)session.load(Number.class, id);
n.setNumber(n.getNumber() +5);
// throw new IllegalArgumentException("BLAH");
session.close();
}
- By commenting out the exception, the update will commit.
- By un-commenting(?) the exception, it will rollback.
Any way to achieve this? Note: the transaction part is done in a service, under a transactional annotation.
DAO is mainly responsible for persistence operations .It should only provide CRUD and some finder methods relating to a particular entity.
IMO , your method more like a business operation rather than the persistence operations . As you have the service layer , I suggest you move this method to it.
So , your NumberDAO may look like this:
And you NumberService may look like this:
As you use transactional annotation in the service layer , it will commit automatically if your service method returns successfully .In case of any exceptions throw before the method returns , the transaction will rollback automatically .