简体   繁体   English

使用JPA重置MySql数据库的自动增量值

[英]Resetting auto-increment value of MySql database with JPA

I just started out writing my first unit tests with JUnit and I ran into a small problem. 我刚开始用JUnit编写我的第一个单元测试,但遇到一个小问题。 Inside my unit-tests i'm inserting new data into my MySql database. 在单元测试中,我正在将新数据插入MySql数据库。 After I added my info, I delete that same info in the next unit test. 添加信息后,我将在下一个单元测试中删除相同的信息。

My table-id is auto-incrementing and with each unit-test I run the value for the next id is incremented with 1. 我的表ID是自动递增的,每次运行单元测试时,下一个ID的值都会递增1。

I implemented a new method with the @AfterClass annotation so that after I'm done with my unit-tests it will reset the increment value. 我使用@AfterClass注释实现了一个新方法,以便在完成单元测试后将重置增量值。 I used this query: 我用这个查询:

entityManager.createNativeQuery("ALTER TABLE student AUTO_INCREMENT = 1");

If I add new info directly into my MySql database the value of the next id isn't what I want it to be (last id value in my table +1). 如果我直接将新信息添加到MySql数据库中,则下一个ID的值不是我想要的值(表+1中的最后一个ID值)。

However when I run the sql-query directly in the database, the query does work. 但是,当我直接在数据库中运行sql-query时,查询确实起作用。

My question: Is it impossible to run these kind of queries while unit-testing? 我的问题:在单元测试中是否不可能运行此类查询? Or am I totally looking at this the wrong way. 还是我完全以错误的方式看待这个问题。

I'm using java, spring, hibernate, jpa , junit 我正在使用java,spring,hibernate,jpa,junit

Thanks in advance! 提前致谢!

You created a query, but forgot to execute it: 您创建了一个查询,但是忘记执行它:

entityManager
    .createNativeQuery("ALTER TABLE student AUTO_INCREMENT = 1")
    .executeUpdate(); 

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

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