【问题标题】:Spring Boot + PostgreSQL: org.postgresql.util.PSQLException: ERROR: null value in column "id" violates not-null constraintSpring Boot + PostgreSQL:org.postgresql.util.PSQLException:错误:“id”列中的空值违反非空约束
【发布时间】:2021-03-05 18:12:31
【问题描述】:

我不明白为什么我突然无法在我的表格框架中保存新对象。

我的实体:

@Entity
@Data
@EqualsAndHashCode(exclude="frameworkSortingType")
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "framework")
public class Framework {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @JsonManagedReference
    @OneToOne(mappedBy = "framework", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private FrameworkSortingType frameworkSortingType;

错误:

Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "id" violates not-null constraint
  Detail: Failing row contains (null, 1, 1, 1, null, 2020-11-23 01:14:43.472, null, 2020-11-23 01:14:43.472, 1, 783772).
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)
    at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:120)
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)

有什么问题? ID 必须设置为 NULL 才能在表中保存新对象!当我想更新某些行时,ID 列不能为空...但我不明白为什么突然我不能在表Framework 中添加新行。最近我只添加了@EqualsAndHashCode(exclude="frameworkSortingType"),因为有时我与FrameworkSortingType 表有循环依赖关系。但我不认为这种变化是我的问题的原因......

我想在 DEV 远程服务器上添加它可以工作,框架是旧表...错误发生在我的计算机本地...

【问题讨论】:

    标签: postgresql spring-boot hibernate jpa


    【解决方案1】:

    您已经使用@Id 注释了 id 字段,这意味着现在 id 是 PRIMARY 键,因此它不会为空。

    GenerationType.AUTO
    

    GenerationType.AUTO 指示持久性提供程序应根据指定的数据库方言选择适当的策略。 AUTO 将自动设置生成的值。它是默认的 GenerationType。如果没有定义策略,默认会考虑AUTO。所有数据库都支持这种策略。

    在这里,我可以看到您正在尝试保存 id =null 时无法执行的操作。所以不要为 id 字段分配任何值。 Spring-boot 会照顾好一切。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      • 2012-11-02
      相关资源
      最近更新 更多