Am facing few issues with multi step transction in hibernate. This is what I am doing.
One of my DAO methods
- Creates a new record in Table A and retrieves the Oracle generated Primary key.
- Updates a row in Table B with the Primary key retrieved in step 1
The code looks something like this:
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
开发者_如何学Cpublic Object myDAOMethos(...){
....
getHibernateTemplate().execute(
new HibernateCallback<Long>() {
public Long doInHibernate(Session session)
throws HibernateException, SQLException {
// Create a new record in table A
session.save(objA);
final long pKey = objA.getId();
// Update the row in table B
org.hibernate.Query query = session
.getNamedQuery("updateBQuery").setLong("idB",pKey...
query.executeUpdate();
}
}
return true;
}
});
}
The method is bound under a transction.
My issue: Everything works fine when I run this code on tomcat. But when i try to exeute a junit test case for this, the update on table B never takes place. Although I can see the update SQL on the console output (hibernate.show_sql=true). No exceptions either! just the insert takes place and thats it.
Not sure what is happening here! any ideas!?
regards, -J
A few things could be wrong
It is suspicious that you are updated a foreign key to your first entity manually; hibernate should do that for you if you set up your relationships correctly.
How is your test class set up? Are you rolling the data back at some point so the tests are transparent? What I am getting at is, if you see the the sql, but then in your test you don't see the data, you are trying to access your data at the wrong time to test -- either the data has not been committed, or the data has already been rolled back (if you are rolling back). One thing you might want to try is turning the tx off, then running the test. Note you will have to clean up the data manually, but it should indicate whether the tx configuration in the test is the problem.
Spring has some base test classes available that manage transactions and rolling data back for you....
thanks for the reply. you are right.
While you would be posting this answer, I realized wht the problem was and tried that, worked!!
It is the point 2 in your post. Basicallly the junit test case itself uses "AbstractTransactionalJUnit4SpringContextTests" and manages the DB commit/rollback after the test via @Rollback. So basically, the data which I was trying to update was not created in the first place. Am still surprized that I didnt not see any errors on the console!!
Am accepting your answer as the right one. Thanks a ton!
-J
精彩评论