[英]Postgresql throws null value in column "id" violates not-null constraint for GenerationType.IDENTITY
I'm trying to autogenerate id's for my entity:我正在尝试为我的实体自动生成 ID:
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我的数据库表是通过 flyway 脚本创建的,列 ID 设置为 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
null “id”列中的值违反了非空约束
This only shows while connected to PostgreSQL:12.2, if I run the same code with h2 database it works fine.这仅在连接到 PostgreSQL:12.2 时显示,如果我使用 h2 数据库运行相同的代码,它工作正常。
Why is this failing in PostgreSQL?为什么这会在 PostgreSQL 中失败?
I'm trying to autogenerate id's for my entity:我正在尝试为我的实体自动生成 id:
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我的DB表是通过flyway脚本创建的,列ID设置为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
“id”列中的 null 值违反非空约束
This only shows while connected to PostgreSQL:12.2, if I run the same code with h2 database it works fine.这仅在连接到 PostgreSQL:12.2 时显示,如果我使用 h2 数据库运行相同的代码,它工作正常。
Why is this failing in PostgreSQL?为什么 PostgreSQL 会失败?
you should create sequence and use that sequence for id您应该创建序列并将该序列用于 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:你应该在 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) }; CREATE TABLE USERS ( ID serial NOT NULL GENERATED BY DEFAULT AS IDENTITY, PRIMARY KEY (ID) };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.