简体   繁体   English

使用@Transactional在JUnit测试中不删除实体

[英]Entity is not deleted in a JUnit test with @Transactional

I use @Transactional annotation on my JUnit tests sometimes. 我有时会在JUnit测试中使用@Transactional注释。 I use @Transactional in JUnit for Lazy fetching collections. 我在JUnit中使用@Transactional来进行Lazy抓取集合。

Currently I have faced with an unknown behavior for me of @Transactional annotation. 目前,我遇到了@Transactional注释的未知行为。

In my database I have one Car entity. 在我的数据库中,我有一个Car实体。 I am deleting this entity in my test. 我在测试中删除了这个实体。 If I use @Transactional on my test, then this entity IS NOT deleted from a database. 如果我在测试中使用@Transactional ,则不会从数据库中删除此实体。 Otherwise if I do not use @Transactional then the entity is deleted. 否则,如果我不使用@Transactional,则删除该实体。 I see this after every test in my database. 我在数据库中的每次测试后都会看到这个。

I have standard entity and repository. 我有标准实体和存储库。 My entity: 我的实体:

@Entity 
public class Car {

    @Id
    @GeneratedValue
    private int id;

    private String model;

    //...constructors, getters and setters }

My repository: 我的存储库:

public interface CarRepository extends JpaRepository<Car, Integer>{
    List<Car> findByModel(String mazda);
}

My test: 我的测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class RelationsTest {

    @Autowired
    CarRepository carRepository;

    @Test
    //@Transactional
    public void deleteCar() throws Exception {

        List<Car> cars = carRepository.findByModel("Mazda");
        assertThat(cars).hasSize(1);

        carRepository.deleteById(cars.get(0).getId());

    }

What is a reason that with @Transactional the entity is not deleted from a database? 使用@Transactional实体未从数据库中删除的原因是什么?

From the Spring Boot documentation : 从Spring Boot 文档

If your test is @Transactional, it rolls back the transaction at the end of each test method by default. 如果您的测试是@Transactional,则默认情况下会在每个测试方法的末尾回滚事务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM