我使用以下方式处理网络项目:
我刚接触Postgres数据库,对于我的桌子,我决定使用(第一次)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:在调用save()之前必须手动分配此类的ID:net.myapp.User;
Followiong 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:错误:运算符不存在:uuid = bytea 提示:没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型转换。
当我尝试创建新记录时:
org.springframework.dao.InvalidDataAccessResourceUsageException:无法执行语句; SQL [不适用];
答案 0 :(得分:3)
我使用了这个配置,这对我和我都有用 我正在使用
Entity.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";
答案 1 :(得分:0)
作为一个魅力:
创建自定义配置类
package mypackage;
public class PostgresUuidDialect extends PostgreSQL9Dialect {
@Override
public void contributeTypes(final TypeContributions typeContributions, final ServiceRegistry serviceRegistry) {
super.contributeTypes(typeContributions, serviceRegistry);
typeContributions.contributeType(new InternalPostgresUUIDType());
}
protected static class InternalPostgresUUIDType extends PostgresUUIDType {
@Override
protected boolean registerUnderJavaType() {
return true;
}
}
}
在 application.properties 中添加
spring.jpa.database平台= mypackage.PostgresUuidDialect
(根据您的需要更改 mypackage )
优点:您不需要在JPA实体中使用任何特殊注释
缺点:项目中的模糊类......