0

I have some hibernate code and I want my code run in 1 transaction let me explain in code

public void changeBranch(Branch branch) throws DatabaseException {
//some code
            humanDao.update(he);
            superBranchUsername = branch.getFatherUsername();
            int superBranchId = branchDao.getBranchIdByUserName(superBranchUsername);
            BranchEntity superBranch = branchDao.load(superBranchId);
            BranchEntity be = new BranchEntity();
            setBranchEntity(be, he, pkId, bname, confirmed, level, studentCount, uname, superBranch);
            branchDao.update(be);   // update kardane jadvale Branch va Set kardane Human motenazer be on
//some code
}

Both humanDao.update(he); and branchDao.update(be); run in transaction handle by My GenericDAO that humanDao and branchDao are inherited from it. but I want this block of code (wrote above) to also run in a transaction!! How can I get to Hibernate to do this?

Xstian
  • 8,184
  • 10
  • 42
  • 72
Am1rr3zA
  • 7,115
  • 18
  • 83
  • 125

3 Answers3

2

DAOs should not handle transactions for exactly the reason you've discovered: they can't know when they're part of a larger transaction.

If you were using Spring declarative transactions, you'd have a service layer that would create the transaction context for both DAOs and deal with everything. I would recommend doing something like that.

UPDATE: I added a link to Spring.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • Tanx but I don't know what is Spring declarative transactions exactly, i must read about this method. – Am1rr3zA Jul 26 '09 at 16:27
  • I'm curious - do you think it's ok for the DAO to (eagerly) flush the hibernate session when it completes it's portion of work, or should it wait for the transaction to end? – matt b Aug 12 '09 at 20:40
  • 1
    I'd wait for the transaction to end. – duffymo Aug 16 '09 at 13:19
1

Please see: Chapter 11. Transactions and Concurrency

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
0

I find how should I fix it if I new session in changeBranch(Branch branch) and pass this session as a parameter to my DAO my problem solved

Am1rr3zA
  • 7,115
  • 18
  • 83
  • 125