我正在使用以下工具开发 Web 项目:
- Spring 4.x (Spring Boot 1.3.3)
- hibernate 4.x
- PostgreSQL 9.x
我是 Postgres DB 的新手,对于我的表,我决定(第一次)使用 UUID
标识符,但我遇到了一些麻烦......
对于 ID 字段,我使用了 Postgres uuid
类型,并将 uuid_generate_v4()
设置为默认值。当我直接通过 PSQL 插入生成新行时,一切正常,但我无法通过我的应用程序创建新记录。
例如,这是我在应用程序中声明实体的方式:
@Entity
@Table(name = "users")
public class User {
@Id
@Type(type = "pg-uuid")
private UUID id;
// other fields and methods...
}
对于此声明,我使用了 Type
Hibernate 注释。
查找 操作运行良好,但是当我尝试进行插入 时,我得到了这个异常:
org.springframework.orm.jpa.JpaSystemException: ids for this class must be manually assigned before calling save(): net.myapp.User;
关注this tutorial我试图解决这个问题。我将实体定义更改为:
@Entity
@Table(name = "users")
public class User {
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(columnDefinition = "BINARY(16)")
@Id
private UUID id;
// other fields and methods...
}
但现在当我从数据库中检索(现有)数据时,我得到了错误的 ID 值(仍然没有尝试插入...)。
那么在我的案例中定义 ID 字段的正确方法是什么?
更新
使用第二个定义...
当我尝试通过 ID 查找时,我得到:
org.postgresql.util.PSQLException: ERROR: operator does not exist: uuid = bytea Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
当我尝试创建新记录时:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a];
最佳答案
我使用了这个配置,这对我有用,而且 我正在使用
- Spring 启动 1.5.2
- hibernate 5
- PostgreSQL 9.6
实体.java
@Id
@Column(updatable = false, nullable = false, columnDefinition = "uuid DEFAULT uuid_generate_v4()")
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
private UUID id;
在此之前,我建议您将 uuid-ossp
加载到您的数据库中以使用它。
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
关于java - 无法为我的实体生成 UUID ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36528580/