【问题标题】:Spring Boot with JPA and H2 with auto increment id column: NULL not allowed for column带有 JPA 和 H2 的 Spring Boot,带有自动递增 id 列:列不允许为 NULL
【发布时间】:2023-02-09 01:33:09
【问题描述】:

我正在尝试关注一个示例项目Spring 安全实战但是使用 H2 而不是 MySQL,我正在努力寻找正确的配置组合来让事情正常工作。

我的简单实体,它只是一个带有主键的简单对象。我将“id”列表现得像一个自动递增的主键,因为数据库应该生成它而不是应用程序。

@Entity
@Getter
@Setter
public class Workout {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String user;
    private LocalDateTime start;
    private LocalDateTime end;
    private int difficulty;
}

我的存储库(没什么特别的):

@Repository
public interface WorkoutRepository extends JpaRepository<Workout, Integer> {
}

控制器的相关部分,它只接收一个没有指定 id 的 Workout 对象并将其保存到数据库中:

@RestController
@RequestMapping("/workout")
public class WorkoutController {
    
    private final WorkoutRepository workoutRepository;

    public WorkoutController(WorkoutRepository  workoutRepository) {
        this.workoutRepository= workoutRepository;
    }
    
    @PostMapping("/")
    public Workout add(@RequestBody Workout workout) {
        return workoutRepository.save(workout);
    }
    
}

还有我的application.properties

spring.datasource.url=jdbc:h2:file:~/fitnessapp;AUTO_SERVER=TRUE;
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
# using this because I have a column called "user" which is a reserved word
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
spring.jpa.hibernate.ddl-auto=update

当我运行它时,应用程序启动,我可以检查 H2 控制台并查看表是否已正确创建。但是,当我提交保存新实体的请求时,出现内部服务器错误。

日志显示生成的 SQL 尝试将“id”列设置为 NULL,这会导致 SQL 错误:

Hibernate: insert into "workout" ("id", "difficulty", "end", "start", "user") values (null, ?, ?, ?, ?)
2023-02-08 16:04:48.427  WARN 22656 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 23502, SQLState: 23502
2023-02-08 16:04:48.427 ERROR 22656 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : NULL not allowed for column "id"; SQL statement:
insert into "workout" ("id", "difficulty", "end", "start", "user") values (null, ?, ?, ?, ?) [23502-200]

因此,即使 JPA 正在为实体定义架构,它似乎也不知道如何将行插入表中。

我已经尝试了GenerationType 策略的许多不同组合,使用schema.sql 文件自己创建了表模式(尽管我宁愿不求助于此,因为 JPA 应该能够为我做到这一点),以及各种休眠属性.似乎没有任何效果。

版本:

  • Spring Boot 父级:2.3.0.RELEASE
  • Spring Data JPA:2.3.0.RELEASE
  • H2:1.4.200

【问题讨论】:

    标签: java spring spring-boot jpa h2


    【解决方案1】:

    您能否也提供您传递给控制器​​的 json?

    【讨论】:

      猜你喜欢
      • 2021-06-23
      • 2017-02-20
      • 1970-01-01
      • 2021-08-17
      • 2018-07-11
      • 1970-01-01
      • 2021-01-21
      • 2019-12-20
      • 1970-01-01
      相关资源
      最近更新 更多