我有一个实体,其 mysql 列定义为 auto_increment
@Column(columnDefinition = "integer auto_increment")
private int entityNumber;
我还有一个 Arquillian 测试,在其中测试该实体的创建和删除。测试类使用注释
@UsingDataSet("datasets/empty.xml")
在下面的代码中,我解释了发生的情况以及我收到的错误
@Test
public void createEntityTest1() {
Entity entity1 = persistEntity();
assertEquals(1, entity1.entityNumber); // works perfectly
}
@Test
public void createEntityTest2() {
Entity entity2 = persistEntity();
assertEquals(1, entity2.entityNumber);
// fails! Since I am in a new test I expect the new entityNumber to be 1
// but it is actually 2 because entity2 was previously created in
// createEntityTest1, although the entity itself doens't exist anymore
//in the DB
}
问题是,每次测试后,auto_increment索引都没有被重置,因此它在我的所有测试中不断增加,当我想检查它时,自动生成的数字大于预期。
有没有办法在每次测试后重置该值?
编辑
我的表的 SQL 架构。这确实是一个简单的事情
CREATE TABLE `entity` (
`id` varchar(36) NOT NULL
`version` bigint(20) NOT NULL,
`entity_number` int(11) NOT NULL AUTO_INCREMENT
PRIMARY KEY (`id`),
UNIQUE KEY `UK_entity_number` (`entity_number`),
KEY `IX_entity_entity_number` (`entity_number`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1
最佳答案
CREATE TABLE `entity` (
`id` varchar(36) NOT NULL,
`version` bigint(20) NOT NULL,
`entity_number` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_entity_number` (`entity_number`),
KEY `IX_entity_entity_number` (`entity_number`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- truncate table entity;
insert entity (id,version) values (8,111),(9,11111);
select * from entity;
+----+---------+---------------+
| id | version | entity_number |
+----+---------+---------------+
| 8 | 111 | 1 |
| 9 | 11111 | 2 |
+----+---------+---------------+
改变的视觉:
ALTER TABLE `entity` AUTO_INCREMENT = 550; -- move it up high
insert entity (id,version) values (700,222233333111);
+-----+--------------+---------------+
| id | version | entity_number |
+-----+--------------+---------------+
| 700 | 222233333111 | 550 |
| 8 | 111 | 1 |
| 9 | 11111 | 2 |
+-----+--------------+---------------+
重置为空:
truncate table entity;
insert entity (id,version) values (88888,111),(999999,11111);
+--------+---------+---------------+
| id | version | entity_number |
+--------+---------+---------------+
| 88888 | 111 | 1 |
| 999999 | 11111 | 2 |
+--------+---------+---------------+
因此您需要决定要执行哪一个:ALTER TABLE
或TRUNCATE TABLE
.
但正如我在另一个 Answer 中所示对于我来说,如果您显式传递 auto_increment 列的列,则可以使用 ALTER 来填补已知的空白。但是您不能将 AI 值移低,不通过 AI 列,并期望填补空白(在这种情况下,max(id) 将自动将 AI 值填充为表中的最高值)。
关于java - 在每次 Arquillian 测试之前重置 AUTO_INCRMENT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38145061/