使用Junit进行测试时,JPA EntityManager值不会保留在数据库中

Jåc*_*cob 4 junit spring hibernate jpa jpa-2.0

我在Spring 3中使用Hibernate 4,当我尝试进行Junit测试时,数据库中不会保留值

在我的DAO实现类中

@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;
    }
Run Code Online (Sandbox Code Playgroud)

在Junit测试我有

@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);
    }
Run Code Online (Sandbox Code Playgroud)

我可以在控制台中看到此语句的值,但是记录不会保存在数据库中.

System.out.println("val  2  -- "+project.getProjectNo());
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Kev*_*sox 12

默认情况下,Spring Test将回滚单元测试中的所有事务,导致它们不出现在数据库中.

您可以通过向测试类添加以下注释来更改默认设置,这将导致提交事务.

@TransactionConfiguration(defaultRollback=false)
@ContextConfiguration({"classpath:applicationContext.xml"})
@Transactional
@RunWith(SpringJUnit4ClassRunner.class) 
public class ProjectTest {
    //Tests here
}
Run Code Online (Sandbox Code Playgroud)

  • 天哪,Stack Overflow 真是一个很棒的论坛。这正是我所缺少的。非常感谢您分享您的知识,并感谢@user75ponic 提出问题。这给我省去了很多麻烦。 (2认同)

Tor*_*oro 6

基于@TransactionConfigurationSpring Framework 4.2发布以来不推荐使用的事实,建议使用@Rollback.

@Rollback(false)
@ContextConfiguration({"classpath:applicationContext.xml"})
@Transactional
@RunWith(SpringJUnit4ClassRunner.class) 
public class ProjectTest {
    //Tests here
}
Run Code Online (Sandbox Code Playgroud)