我正在使用spring-boot-starter-data-jpa。如果我的代码没有注释,我应该在实体ID上使用注释@GeneratedValue并在mysqldb中自动生成PRIMARY KEY吗?

当我在sqltable中运行测试时,会出现一个新行,该行的ID具有以下AUTO_INCREMENT值,而每次传递的id为0。

实体

@Data
@Entity
@RequiredArgsConstructor
@NoArgsConstructor(access = AccessLevel.PRIVATE, force = true)
public class Person {

    @Id
//  @GeneratedValue(strategy = GenerationType.IDENTITY)// use or not - the same effect
    private int id;
    @NonNull
    private String name;
    @NonNull
    private String surname;
}


资料库

public interface PersonRepository extends CrudRepository<Person, Integer> {
    Person findByNameAndSurname(String name, String surname);
}


测试中

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringRestInventoryPersistenceTests {

    @Autowired
    private PersonRepository personRepository;

    @Test
    public void personPersist() {
        Person person = new Person("John", "Smith");
        assertTrue(person.getId() == 0);
        personRepository.save(person);
        assertTrue(person.getId() == 0);
        Person person2 = personRepository.findByNameAndSurname("John", "Smith");
        assertEquals(person.getName(), person2.getName());
    }//test passed


mySql表

CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `surname` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8

最佳答案

我也遇到了同样的问题,我在数据库中添加了序列发生器,说“ idGenerator”,然后添加

@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="idGenerator") @SequenceGenerator(name='dbname' , sequenceName="idGenerator")

这将从数据库中创建的序列生成器中获取值

10-06 05:38