简体   繁体   中英

Spring Data JPA "null value in column xxx violates not-null constraint" on serial column with postgresql

My entity has a mapOrder field which I want auto-increment like below:

@Entity
public class Map{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(columnDefinition = "serial")
    private Long mapOrder;

    //.......
}

The sql generated seems good:

CREATE TABLE map
(
  id bigserial NOT NULL,
  map_order serial NOT NULL,
  ...
)

But when I save it with Spring Data JPA's repository, like this:

Map m=new Map();
repo.save(m);

will give me exception:

Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "map_order" violates not-null constraint

Any ideas?

Try changing your code to this:

@GeneratedValue(strategy = GenerationType.SEQUENCE)

Reference: https://stackoverflow.com/a/29028369

@GeneratedValue works with identifiers and you can't use it with regular fields.

You can, for example, use some object for sequences (with any key generation strategy):

@Entity
public class JpaNoPkSequence {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id", nullable=false, updatable=false)    
    private Long id;
}

For using the strategy GenerationType.SEQUENCE the sequence should be created in the database:

CREATE SEQUENCE JPA_PK_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
ALTER SEQUENCE "JPA_PK_SEQ" OWNER TO something;

This should be specified in the key definition. You should also add a one-to-one relationship with the object that you will use to obtain sequences for regular fields:

@Entity 
public class Map {
    @Id
    @SequenceGenerator(name="jpaPkSeq", sequenceName="JPA_PK_SEQ", allocationSize=1, initialValue = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "jpaPkSeq")
    @Column(name = "id", nullable=false, updatable=false)
    private Long id;

    @OneToOne           
    private JpaNoPkSequence sequence;
    ...
}   

Hope this helps.

I had the same problem. In my case, the error was in creating the table.

You need to use SERIAL type instead of others (at least in Postgres).

Before (bigint type)

CREATE TABLE IF NOT EXISTS sample_table

(
    id BIGINT NOT NULL,
    ...
);

After (serial type)

CREATE TABLE IF NOT EXISTS sample_table

(
    id SERIAL NOT NULL,
    ...
);

The id in the entity class looked like this:

@Id
    @GeneratedValue(strategy = IDENTITY)
    private Long id;

This question is full of bad advice. The problem is the second column with a serial value. The problem is that Hibernate explicitly inserts a null there. You have to tell it not to.

@Column(columnDefinition = "serial", insertable = false)
private Long mapOrder;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM