Java 使用Hibernate允许ID=0(“eclipselink.ID验证”等效于“NULL”)
我正在使用hibernate 5.0.12和springboot 1.5.14 我的实体有这个idJava 使用Hibernate允许ID=0(“eclipselink.ID验证”等效于“NULL”),java,hibernate,identity,Java,Hibernate,Identity,我正在使用hibernate 5.0.12和springboot 1.5.14 我的实体有这个id @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "UserID", nullable = true) public int getUserId() { return this.userId; } public void setUserId(int userId) { this.userId
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "UserID", nullable = true)
public int getUserId() {
return this.userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
在我的数据库中显示的是id为0的记录
如果我读取、编辑并保存这些记录,hibernate将使用生成的新id复制这些记录
如何配置hibernate以允许id=0
值
在eclipselink中,此配置是
“eclipselink.id validation”=“NULL”
您应该编辑数据库,而不是hibernate配置,尽管这是一种不好的做法
解决方案是将主键类型声明为整数而不是int
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "UserID", nullable = true)
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
这个问题应该与数据库相关,因为即使您显式地为Long/Int主键设置了零值(由于大多数数据库的默认设置方式),数据库通常也会“更正”您的输入 例如,对于MySQL,您可以显式地将ID设置为零(0),但数据库仍将忽略它,除非您为您的
sql\u模式添加/设置NO\u AUTO\u VALUE\u ON\u zero
。
如果MySQL/MariaDB是这种情况,您可以在my.cnf
文件中直接更改,如果您不想重置数据库,则需要通过set global sql\u mode='NO\u AUTO\u VALUE\u ON\u ZERO'进行设置。
我认为这个答案是相关的,因为您使用了@GeneratedValue(strategy=GenerationType.IDENTITY)
这不是我的要求。数据库已接受0个值。记录已存在此值。我的数据库是SAP SQL Anywhere 17。默认情况下,它允许自动增量字段为零值。在我的数据库中,autoincrement只计算空值。