我有一个带有 h2 数据库的 spring boot 项目。
我有一个要从中生成架构的实体类:
@NoArgsConstructor
@Entity
@Table(name = "NAMES")
public class Name {
@Id
@GeneratedValue
public Long id;
@Column(nullable = false)
public String name;
public Name(String name) {
this.name = name;
}
}
我有一个data.sql
文件:
insert into names (id, name) values (1, 'Alex');
insert into names (id, name) values (2, 'Bob');
我的 application.properties 是:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.defer-datasource-initialization=true
spring.jpa.show-sql=true
应用程序启动得很好,我可以通过 localhost:8080/h2-console 确认数据已加载到数据库中。但我无法将新数据保存到表中
//public interface NameRepository extends CrudRepository<Name,Long> {}
@RestController
@Service
public class MyController {
@Autowired
private final NameRepository nameRepository;
@PostMapping("/triggerError")
public ResponseEntity<Void> trigger() {
Name newName = new Name("Chris");
nameRepository.save(newName);
return ResponseEntity.ok().build();
}
}
错误信息是:
could not execute statement; SQL [n/a]; constraint [\"PRIMARY KEY ON PUBLIC.NAMES(ID) ( /* key:1 */ CAST(1 AS BIGINT), 'Alex')\"; SQL statement:
insert into names (name, id) values (?, ?) [23505-210]];
我假设这意味着 spring 想要在 id=1 处插入新名称,而没有意识到 ids 1 和 2 已经在使用中。我想正确的参数@GeneratedValue
可以修复它,但我不明白它们的含义以及选择哪一个。
试验和错误:
@GeneratedValue(strategy = GenerationType.AUTO)
是默认值,见上文。
@GeneratedValue(strategy = GenerationType.TABLE)
相同的错误
@GeneratedValue(strategy = GenerationType.SEQUENCE)
相同的错误
@GeneratedValue(strategy = GenerationType.IDENTITY)
不同的错误:
...
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column \"ID\"; SQL statement:\ninsert into names (id, name) values (null, ?) [23502-210]
...
could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
所以显然它不是注释,而是别的东西。
我放弃了,这是我的 MRE:https ://github.com/timo-a/duckpond-spring-backend/tree/debug/saving