简体   繁体   中英

Postgresql throws null value in column "id" violates not-null constraint for GenerationType.IDENTITY

I'm trying to autogenerate id's for my entity:

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

My DB table is created via flyway script, and column ID is set as IDENTITY

CREATE TABLE USERS (
   ID INT NOT NULL GENERATED BY DEFAULT AS IDENTITY,
   PRIMARY KEY (ID)
};

Then I'm trying to save this entity with my repository:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {}

like this:

userRepository.save(user);

however this results in an error

null value in column "id" violates not-null constraint

This only shows while connected to PostgreSQL:12.2, if I run the same code with h2 database it works fine.

Why is this failing in PostgreSQL?

I'm trying to autogenerate id's for my entity:

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

My DB table is created via flyway script, and column ID is set as IDENTITY

CREATE TABLE USERS (
   ID INT NOT NULL GENERATED BY DEFAULT AS IDENTITY,
   PRIMARY KEY (ID)
};

Then I'm trying to save this entity with my repository:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {}

like this:

userRepository.save(user);

however this results in an error

null value in column "id" violates not-null constraint

This only shows while connected to PostgreSQL:12.2, if I run the same code with h2 database it works fine.

Why is this failing in PostgreSQL?

you should create sequence and use that sequence for id

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id_seq")
    @SequenceGenerator(name = "user_id_seq", sequenceName = "user_id_seq")
    private long id;

and you should create sequence in postgresql:

CREATE SEQUENCE user_id_seq
INCREMENT 5
START 10;

make users table

CREATE TABLE USERS ( ID serial NOT NULL GENERATED BY DEFAULT AS IDENTITY, PRIMARY KEY (ID) };

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