非空约束上的休眠 JoinColumn 错误

use*_*206 1 java entity-framework hibernate

这是我的课程列表

@MappedSuperclass
public abstract class JpaModel {

    @Id
    @Column(name ="ID", columnDefinition = "serial")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
}
Run Code Online (Sandbox Code Playgroud)

产品实体

@Entity
@Table(name = "REF_PRODUCT")
public class Product extends JpaModel{

    @Column(name= "NAME")
    private String name;

    @Column(name = "MANUFACTURER")
    private String manufacturer;

    /**
     * Work around for missing
     */
    @OneToOne(optional = true)
    @JoinColumn(name="id")
    private InventoryItemPicture picture;
Run Code Online (Sandbox Code Playgroud)

.... }

和库存物品图片实体

@Entity
@Table(name = "TXN_INVENTORY_PICTURE")
public class InventoryItemPicture extends JpaModel{

    @Column
    private byte[] image;

    @Column
    private String fileName;
Run Code Online (Sandbox Code Playgroud)

保存产品时,inventoryItemPicture 是可选的,因此有时它会是空值,这是我希望发生的事情。但是,在使用空值保存产品实体时,会出现此错误。

Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "id" violates not-null constraint
  Detail: Failing row contains (null, null, test, dsadas, sdas, dsadsa, 500.00, 1000.00, 1500.00, 5, PRODUCT).
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2198)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1927)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:561)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:419)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:365)
    at com.zaxxer.hikari.proxy.PreparedStatementProxy.executeUpdate(PreparedStatementProxy.java:61)
    at com.zaxxer.hikari.proxy.PreparedStatementJavassistProxy.executeUpdate(PreparedStatementJavassistProxy.java)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    ... 120 more
Run Code Online (Sandbox Code Playgroud)

小智 5

从您的日志中,它显示id=null,它根本与inventoryItemPicture 无关。

问题在 @GeneratedValue(strategy = GenerationType.IDENTITY)

您的日志显示您正在使用 postgresql,但“IDENTITY”只能用于这些数据库:

  • Sybase、My SQL、MS SQL Server、DB2 和 HypersonicSQL。

您应该使用GenerationType.SEQUENCE,它支持:

  • Oracle、DB2、SAP DB、Postgre SQL 或 McKoi。

尝试将您的代码更改为:

@GeneratedValue(strategy = GenerationType.SEQUENCE)
Run Code Online (Sandbox Code Playgroud)