当前位置: 首页 > 知识库问答 >
问题:

当前线程没有实际事务可用的EntityManager

斜瑞
2023-03-14

此错误发生在This.ItemRepository.DeleteAll(),当SampleTest()方法运行时。

@ExtendWith(SpringExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Rollback(false)
public class ScheduleTests {

    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduleTests.class);

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private ItemRepository itemRepository;

    @Autowired
    private ItemQualifierRepository itemQualifierRepository;

    @Autowired
    private MappingRepository mappingRepository;

    @BeforeAll
    public void setUp() {
        restoreInitialData();
        LOGGER.info("Initial data restored");
    }

    @Test
    public void sampleTest() {
        File feed = new File("target/test-classes/TestFeedOK.json");
        Feed.ingest(feed);
        LOGGER.info("Feed {} ingested", feed.getName());
    }

    private void restoreInitialData() {
        this.itemRepository.deleteAll();
        this.mappingRepository.deleteByTableName("event");
    }
}

RestoreInitialData()添加@transaction注释不能解决问题-https://stackoverflow.com/a/32552558/3536552

你知道怎么修吗?

共有1个答案

裴凯定
2023-03-14

我认为问题在于RestoreInitialData是从setup调用的,这是一个@BeforeAll方法。Spring当时还没有介入创建事务。只需将其更改为@Beforeech,并使用@Transactional进行检查。如果你想让某件事只执行一次。尝试这种方法

private static boolean setUpIsDone = false;
.....
public void setUp() {
    if (setUpIsDone) {
        return;
    }
    // do the setup
    setUpIsDone = true;
}
 类似资料: