如何在数据库中生成一个字符串主键,并通过JPA注释来定义它。

问题描述 投票:0回答:1

我想拥有一个带有字符串pk的实体,它是由数据库生成的,带有静态前缀和序列。当我试图通过我的spring应用程序插入一条新的记录时,我得到这个错误。谁能帮帮我?

我的错误。

"Unknown integral data type for ids : java.lang.String; nested exception is org.hibernate.id.IdentifierGenerationException: Unknown integral data type for ids : java.lang.String"

我的表 sql:

CREATE sequence octo_reference_code;

SELECT setval('octo_reference_code', 1010);

create table user_references
(
code text not null default 'octo' || nextval('octo_reference_code')
    constraint user_references_pk
        primary key,
user_id uuid
    constraint user_references_users_id_fk
        references users,
create_date timestamptz default now()
);

我的实体类pk定义。

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "code", columnDefinition = "text", nullable = false, updatable = false)
public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}
spring postgresql spring-boot jpa spring-data-jpa
1个回答
0
投票

你需要将序列转换为TEXT。 添加 ::TEXT 到头来 nextval() 调用。

code text not null default 'octo' || nextval('octo_reference_code')::TEXT


0
投票

你可以定义你的ID使用你在数据库中定义的序列,为此你可以添加以下内容。

    @Id
    @SequenceGenerator(name = "octo_reference_code", sequenceName = "octo_reference_code", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "octo_reference_code")
    @Column(name = "code")
    public String getCode() {
        return code;
    }
© www.soinside.com 2019 - 2024. All rights reserved.