Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA EntityManager values are not persisted in database when tested using Junit

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?

like image 356
Jacob Avatar asked Jul 22 '13 08:07

Jacob


2 Answers

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
}
like image 50
Kevin Bowersox Avatar answered Nov 20 '22 09:11

Kevin Bowersox


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
}
like image 44
Toro Boro Avatar answered Nov 20 '22 09:11

Toro Boro