public interface CarRepository extends JpaRepository<Car, Integer>
, JpaSpecificationExecutor<Car> {
@Modifying
@Query("update Car c set c.status = :newStatus where c.id = :carId and c.status = :oldStatus")
void updateStatusById(@Param(value = "carId") int carId, @Param(value = "oldStatus") int oldStatus, @Param(value = "newStatus") int newStatus);
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class CarRepositoryTest {
@Resource
CarRepository carRepository;
@Transactional
@Test
public void updateStatusById(){
carRepository.updateStatusById(1,0,1);
carRepository.updateStatusById(2,1,0);
}
}
发现Junit测试成功,但查看数据库中的数据并未更新成功
于是查看日志输出发现最后有一行如下
2019-05-19 22:50:12.985 INFO 4204 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test:
原来是事务回滚的缘故,对代码进行如下改动可以阻止事务回滚,注意@Transactional的位置
public interface CarRepository extends JpaRepository<Car, Integer>
, JpaSpecificationExecutor<Car> {
@Transactional
@Modifying
@Query("update Car c set c.status = :newStatus where c.id = :carId and c.status = :oldStatus")
void updateStatusById(@Param(value = "carId") int carId, @Param(value = "oldStatus") int oldStatus, @Param(value = "newStatus") int newStatus);
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class CarRepositoryTest {
@Resource
CarRepository carRepository;
@Test
public void updateStatusById(){
carRepository.updateStatusById(1,0,1);
carRepository.updateStatusById(2,1,0);
}
}