gpt4 book ai didi

java - 将空值添加到 NOT NULL 表,org.hibernate.exception.ConstraintViolationException

转载 作者:行者123 更新时间:2023-12-02 07:34:02 24 4
gpt4 key购买 nike

使用hibernate进行数据访问。

我在数据库中有一个列:

varchar(40), default value is set to 0, NOT NULL

我有一个案例,用户发送空值,并收到错误:

Error: org.hibernate.exception.ConstraintViolationException: Cannot insert the value
NULL into column 'foo', table 'MyTable'; column does not allow nulls. INSERT fails.

hibernate中的列定义如下:

@Column(name = "foo")
private String foo;

问题可能出在哪里?我必须在 hibernate 注释或其他东西中定义默认值吗?如何?或者还有其他建议吗?

最佳答案

尝试将 NULL 插入 NOT NULL 列时,您预计会发生什么?您想要强制执行 NOT NULL 约束,然后需要拒绝用户输入,或者您想要接受 NULL 值并需要指定该列可为空当然,使用@Column(nullable = true)

<小时/>

因为当用户不提供该字段时,您实际上希望在列中使用默认值,并且您的代码显式设置该字段值,即使它为 null(或空,例如,对于 Oracle 来说是相同的),我建议在场上配备更聪明的二传手:

private String foo = "0";

public String getFoo() {
return foo;
}

public void setFoo(String foo) {
if (foo != null && !foo.isEmpty()) { // Or StringUtils.isNotBlank(foo)
this.foo = foo;
}
}

关于java - 将空值添加到 NOT NULL 表,org.hibernate.exception.ConstraintViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12510186/

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