使用JPA重置MySql数据库的自动增量值 [英] Resetting auto-increment value of MySql database with JPA

查看:276
本文介绍了使用JPA重置MySql数据库的自动增量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始用JUnit编写我的第一个单元测试,但遇到一个小问题. 在单元测试中,我正在将新数据插入MySql数据库.添加信息后,我将在下一个单元测试中删除相同的信息.

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.

我的表ID是自动递增的,在每次单元测试中,我运行的下一个ID的值都会递增1.

My table-id is auto-incrementing and with each unit-test I run the value for the next id is incremented with 1.

我使用@AfterClass注释实现了一个新方法,以便在完成单元测试后将重置增量值.我使用了以下查询:

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");

如果我直接将新信息添加到MySql数据库中,则下一个ID的值不是我想要的值(我的表+1中的最后一个ID值).

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

但是,当我直接在数据库中运行sql-query时,查询确实起作用.

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.

我正在使用java,spring,hibernate,jpa,junit

I'm using java, spring, hibernate, jpa , junit

提前谢谢!

推荐答案

您创建了查询,但是忘记执行它:

You created a query, but forgot to execute it:

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

这篇关于使用JPA重置MySql数据库的自动增量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆