Spring JPA Junit 关闭自动回滚

使用JPA配合Hibernate ,采用注解默认是开启了LayzLoad也就是懒加载,所以不得不在Junit的单元测试上加上@Transactional注解,这样Spring会自动为当前线程开启Session,这样在单元测试里面懒加载才不会因为访问完Repository之后,出现session not found.
但是单元测试里面如果加上了@Transactional 会自动回滚事务,需要在单元测试上面加上@Rollback(false),这样才能插入数据库

    @Test
    @Transactional
    @Rollback(false) //关闭自动回滚
    public void saveTest() {
        ProductCategory category = new ProductCategory();
        category.setCategoryname("快乐");
        category.setCategorytype(6);
        ProductCategory save = categoryRepository.save(category);
        System.out.println(save.toString());
    }

控制台打印的日志,显示提交事务

Hibernate: insert into product_category (category_name, category_type) values (?, ?)
ProductCategory{categoryid=8, categoryname='快乐', categorytype=6}
2018-06-27 14:10:17,310 - Committed transaction for test context [DefaultTestContext@120d6fe6 testClass = ProductCategoryRepositoryTest, testInstance = com.company.repository.ProductCategoryRepositoryTest@58d4238e, testMethod = saveTest@ProductCategoryRepositoryTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@4ba2ca36 testClass = ProductCategoryRepositoryTest, locations = '{}', classes = '{class com.company.SellApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@4bec1f0c, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6adede5, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@49993335, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@5f9d02cb], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].

猜你喜欢

转载自blog.csdn.net/damon_01/article/details/80828535