JPA EntityManager values ​​not stored in database when testing with Junit

I am using Hibernate 4 with Spring 3, and when I try to run the Junit test, the values ​​are not stored in the 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 the 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 can see the value for this statement in the console, although the record is not saved in the database.

 System.out.println("val 2 -- "+project.getProjectNo()); 

How can I solve this problem?

+4
source share
2 answers

By default, Spring Test will roll back all transactions in the unit test so that they do not appear in the database.

You can change the default setting by adding the following annotation to the test class, which will result in transactions.

 @TransactionConfiguration(defaultRollback=false) @ContextConfiguration({"classpath:applicationContext.xml"}) @Transactional @RunWith(SpringJUnit4ClassRunner.class) public class ProjectTest { //Tests here } 
+11
source

Based on the fact that @TransactionConfiguration is deprecated since Spring Framework 4.2 came out, it is recommended to use @Rollback .. p>

 @Rollback(false) @ContextConfiguration({"classpath:applicationContext.xml"}) @Transactional @RunWith(SpringJUnit4ClassRunner.class) public class ProjectTest { //Tests here } 
+4
source

Source: https://habr.com/ru/post/1492661/


All Articles