我有一个实体定义,如(getters,setters not shown):
@Entity
public class Employee {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
}
在JUnit中我试图插入一个新的实体。在JUnit之前,我将几条记录加载到Employee表中。 JUnit如下所示:
@RunWith(SpringRunner.class)
@SpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
@Sql("/data/developers.sql")
public class DeveloperRepositoryTest {
@Autowired
private DeveloperRepository developerRepository;
@Test
public void shouldAddNewDeveloper() {
// given
Developer developer = new Developer();
developer.setFirstName("Adam");
developer.setLastName("AAA");
developer.setExperienceLevel(ExperienceLevelEnum.SENIOR);
developer.setProgrammingLanguages(Arrays.asList(ProgrammingLanguage.JAVA, ProgrammingLanguage.C_SHARP));
// when
developerRepository.save(developer);
Iterable<Developer> developers = developerRepository.findAll();
// then
assertThat(developers.iterator().hasNext(), is(true));
assertThat(developers.spliterator().getExactSizeIfKnown(), is(6l));
}
}
在/deta/developers.sql中我插入了5条新记录,所以在保存新实体时我希望将id设置为6.但不幸的是SpringData(Hibernate)没有看到退出的id值并尝试插入新的id值为1的记录和异常发生者。当我将生成策略改为SEQUENCE时,它可以工作。我有点惊讶,因为它没有任何问题,但当我再次尝试执行它时突然失败。如果我尝试使用IDENTITY策略执行它,它也会失败。这有什么问题?