I tried to implement integration test with JUnit and spring. My transactions are not managed by spring, and I prefer manage them by hand (programmatically).
I tried to test it with the simplest example, I create a new item in a user table and I want to keep my database unchanged after the test, that's why I used
spring test's transaction, but I don't know why, my db is never cleaned even if I can see the rollback execution.
My configuration :
My test class :
Both tests insert my user, if run them separately, but after the execution my user is still persisted and not rolled back.
It seems that Hibernate uses an autocommit set to true, I tried to change this parameter with hibernate and c3p0 parameters
So if someone can tell me what I am doing wrong, it would be great.
Thanks for your help.
What are you really testing here? The code under test is in the test? Also this is not going to be portable at all typically for integration type tests you would use an embedded database. Where are you telling spring to manage your transactions? Also try adding <tx:annotation-driven/> to your config.
I know it does not look like an integration test, I just want to be able to simulate an integration test
so try to insert or update a data check if all the mechanism works then rollback the transaction.
That's why I duplicated the persistence code in the test class.
As you can see I use simple Hibernate session without transaction, in my context I did not
link transaction to spring.
If I understand to get it working, I need to link transactions to spring.
Did you add the tag I mentioned to your spring configuration?
Joined: Mar 19, 2012
Yes, but it doesn't work
Joined: Mar 19, 2012
After a while, 2 weeks, I figured out my problem,
on spring logs I realized that my session used by spring transaction and my dao's session was not the same.
That's why when I persisted with my dao, all data were commited.
Why these session were not the same ?
In my dao, I used an hibernate session got from my session factory, and this session was managed throw a ThreadLocal,
when I want to get a session I check the thread local, if an existing one is present I return it otherwise I create a new one
and set it in my threadLocal instance for later calls.
I never checked my sessionFactory.getCurrentSession, my problem was here, because when spring will get its transaction
it will also get a session from the sessionFactory, then to get this session for my dao, the only way I have is to check the sessionFactory.currentSession.