使用postgresql在串行列上的Spring Data JPA"列xxx中的空值违反非空约束"

Jul*_*uly 8 java postgresql hibernate jpa spring-data-jpa

我的实体有一个mapOrder字段,我希望自动增加,如下所示:

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

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

    //.......
}
Run Code Online (Sandbox Code Playgroud)

生成的sql似乎很好:

CREATE TABLE map
(
  id bigserial NOT NULL,
  map_order serial NOT NULL,
  ...
)
Run Code Online (Sandbox Code Playgroud)

但是当我使用Spring Data JPA的存储库保存它时,如下所示:

Map m=new Map();
repo.save(m);
Run Code Online (Sandbox Code Playgroud)

会给我例外的:

Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "map_order" violates not-null constraint
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

小智 5

@GeneratedValue与标识符一起使用,但不能将其与常规字段一起使用。

例如,您可以将某些对象用于序列(使用任何密钥生成策略):

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

为了使用该策略,GenerationType.SEQUENCE应在数据库中创建序列:

CREATE SEQUENCE JPA_PK_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
ALTER SEQUENCE "JPA_PK_SEQ" OWNER TO something;
Run Code Online (Sandbox Code Playgroud)

这应该在键定义中指定。您还应该添加one-to-one与用于获取常规字段序列的对象的关系:

@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;
    ...
}   
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。


小智 4

尝试将您的代码更改为:

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

参考: https: //stackoverflow.com/a/29028369