Reputation: 485
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();
}
Any way to achieve this? Note: the transaction part is done in a service, under a transactional annotation.
Upvotes: 1
Views: 1908
Reputation: 723
commit is not always committing to the db, it is setting at the session cache that this has to be committed, then when you will do flush (also depending on the configuration) the commit will go to the DB, or when the session/transaction ends.
So if you want to force it use flush() after commit. If you can wait check after the session/transaction is being closed.
Upvotes: 0
Reputation: 90557
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:
public class NumberDAO {
public Number loadById(long id){ }
}
And you NumberService may look like this:
public class NumberService{
//Inject by DI containers , or setter / constructor
NumberDAO numberDAO;
public void incrementNumber(long id , int increaseAmount) throws Exception{
Number n = (Number) numberDAO.loadById(id);
if (XXXXXXXX)
throws new IllegalArgumentException("BLAH BLAH BLAH BLAH");
n.setNumber(n.getNumber() +increaseAmount);
}
}
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 .
Upvotes: 1