gpt4 book ai didi

postgresql - 使用实体中的默认值与 PostgreSQL hibernate

转载 作者:行者123 更新时间:2023-12-05 09:08:59 24 4
gpt4 key购买 nike

我正在使用 Springboot 和 PostgreSQL 12 开发 API。我用 hibernate 创建了一个用户表,有问题的实体字段如下:

@Column(columnDefinition = "BOOLEAN NOT NULL DEFAULT FALSE")
private Boolean emailVerificationStatus = false;

我的表格似乎已正确生成:

create table users (
id int8 generated by default as identity,
email varchar(120) not null,
email_verification_status boolean default false not null,
email_verification_token varchar(255),
encrypted_password varchar(255) not null,
first_name varchar(50) not null,
last_name varchar(50) not null,
user_id varchar(255) not null,
primary key (id)
)

我的问题是在运行应用程序时收到一条错误消息:

org.hibernate.PropertyValueException: not-null property references a null or transient value : fr.mycompany.app.io.entity.UserEntity.emailVerificationStatus

默认情况下,当我创建用户时,它会发送一个空值。我可以通过在我的服务层中将值设置为 false 来解决这个问题,但它不是很优雅。此外,当我删除选项 nullable = false 时,它​​工作正常但值设置为 null 而不是获取默认值。当我尝试将用户发送到我的 API 时,postgresql 似乎没有将默认值 (false) 作为值。我想在默认情况下强制将 null 值更改为 false。

最佳答案

根据hibernate documentation您可以尝试使用以下方法:

@Entity
@DynamicInsert
public class YourEntity {

@ColumnDefault("false")
private Boolean emailVerificationStatus;

// ...
}

请注意,上面的实体使用 @DynamicInsert 注释进行注释,因此 INSERT 语句不包含任何不包含值的实体属性。因此,这可以让您避免@MikeOrganek 的回答中描述的情况。

关于postgresql - 使用实体中的默认值与 PostgreSQL hibernate ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62830411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com