junit单元测试dao层遇到的事务问题

来源:互联网 发布:怎么查看路由器端口 编辑:程序博客网 时间:2024/06/05 01:10

1、首先在src/test/java文件下写好测试代码,类名的命名规则,DaoTest.java(建议),方法的命名规则,testAdd,我不以test开头时会报错,报错信息如下:initializationError(org.junit.runner.manipulation.Filter)   java.lang.Exception: No tests found matching;测试方法不能有返回值,不能有参数,当有返回值和参数时也会报错。


2、项目中我使用声明式事务(注解)@Transactional加在了service层,dao层用到了getCurrentSession()方法,会报错,信息如下:

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread

解决方法有两个:将getCurrentSession()改为openSession(),关于两个方法的区别请自行百度,使用了openSession()需要自己关闭session,而使用getCurrentSession()不能自己关闭,否则会报错:

org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: commit failed

另一个办法是在dao层方法的上面也加上@Transactional。