简体   繁体   中英

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. Inside my unit-tests i'm inserting new data into my MySql database. 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.

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. 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).

However when I run the sql-query directly in the database, the query does work.

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

Thanks in advance!

You created a query, but forgot to execute it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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