user962206
user962206

Reputation: 16147

Hibernate JoinColumn Error on not null constraint

Here's a list of my classes

@MappedSuperclass
public abstract class JpaModel {

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

The Product Entity

@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;

.... }

and the inventory item picture entity

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

    @Column
    private byte[] image;

    @Column
    private String fileName;

When saving the Product, The inventoryItemPicture is Optional, thus there will be times that it will be of null value, which is something I would want to happen. However upon saving the Product Entity with a null value this error shows up.

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

Upvotes: 1

Views: 5530

Answers (1)

XLi
XLi

Reputation: 164

From your log, it shows id=null, which is not related to inventoryItemPicture at all.

The issue is at @GeneratedValue(strategy = GenerationType.IDENTITY)

Your log shows you are using postgresql, but "IDENTITY" can only be used for these dbs:

  • Sybase, My SQL, MS SQL Server, DB2 and HypersonicSQL.

You should use GenerationType.SEQUENCE, which is supported by:

  • Oracle, DB2, SAP DB, Postgre SQL or McKoi.

Try change your code to this:

@GeneratedValue(strategy = GenerationType.SEQUENCE)

Upvotes: 5

Related Questions