I use @Transactional annotation on my JUnit tests sometimes. I use @Transactional in JUnit for Lazy fetching collections.
Currently I have faced with an unknown behavior for me of @Transactional annotation.
In my database I have one Car entity. I am deleting this entity in my test. If I use @Transactional on my test, then this entity IS NOT deleted from a database. Otherwise if I do not use @Transactional then the entity is deleted. 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?
From the Spring Boot documentation:
If your test is @Transactional, it rolls back the transaction at the end of each test method by default.