I am using Hibernate 4 with Spring 3 and when I try to do Junit test, values are not persisted in database
In my DAO implementation class
@Transactional
@Repository
public class ProjectDAOImpl extends GenericDAOImpl<Project>
implements ProjectDAO {
public void create(Project project) {
entityManager.persist(project);
System.out.println("val 2 -- "+project.getProjectNo());
}
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
and in Junit test I have
@TransactionConfiguration
@ContextConfiguration({"classpath:applicationContext.xml"})
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
public class ProjectTest {
@Resource
ProjectService projectService;
@Test
public void createProject(){
Project project = new Project();
project.setProjectName("999---");
projectService.create(project);
}
I am able to see the value for this statement in console though, however record is not saved in database.
System.out.println("val 2 -- "+project.getProjectNo());
How can I resolve this issue?
By default Spring Test will rollback all transactions in a unit test causing them not to appear in the database.
You can change default setting by adding the following annotation to the test class, which will cause the transactions to be committed.
@TransactionConfiguration(defaultRollback=false)
@ContextConfiguration({"classpath:applicationContext.xml"})
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
public class ProjectTest {
//Tests here
}
Based on the fact that @TransactionConfiguration is deprecated since Spring Framework 4.2 came out it's recommended to use @Rollback.
@Rollback(false)
@ContextConfiguration({"classpath:applicationContext.xml"})
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
public class ProjectTest {
//Tests here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With