java – JPA 2(EclipseLink)尝试使用UUID作为主键EntityManager.find()总是抛出异常(Database is PostgreSQL)

前端之家收集整理的这篇文章主要介绍了java – JPA 2(EclipseLink)尝试使用UUID作为主键EntityManager.find()总是抛出异常(Database is PostgreSQL)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在尝试使用JPA 2(EclipseLink)将UUID用于主键.我正在使用Postgresql作为数据库.我的实体声明如下:我有一个Employee表,其PK设置为UUID.我有一个JPA实体映射到employee表,如下所示:

@H_502_6@@Entity
public class Employee {
    @Id
    private String id;
    ...
    ...
}

当我调用EntityManager.find(Employee.class,id)时

我从postgres得到一个例外:

内部异常:org.postgresql.util.PsqlException:错误:运算符不存在:uuid =字符变化

提示:没有运算符匹配给定的名称和参数类型.您可能需要添加显式类型转换.

我也尝试将Employee类中的id更改为java.util.UUID,但后来我得到以下(非常类似的错误):

内部异常:org.postgresql.util.PsqlException:错误:运算符不存在:uuid = bytea
提示:没有运算符匹配给定的名称和参数类型.您可能需要添加显式类型转换.

我真的不确定如何解决这个问题……任何人都有任何想法?

谢谢!

最佳答案

I’m trying to use a UUID for a primary key using JPA 2 (EclipseLink)

遗憾的是,标准JPA不包含UUID作为生成标识符的策略.

I have also tried changing the id in the Employee class to java.util.UUID (…)

这不是Id的有效类型(在您的情况下已被视为Serializable). JPA 2.0规范声明:

2.4 Primary Keys and Entity Identity

A simple primary key or a field or property of a composite primary key
should be one of the following types:
any Java primitive type; any primitive
wrapper type; @H_502_6@java.lang.String;
@H_502_6@java.util.Date; @H_502_6@java.sql.Date;
@H_502_6@java.math.BigDecimal;
@H_502_6@java.math.BigInteger
. If the
primary key is a composite primary key
derived from the primary key of
another entity,the primary key may
contain an attribute whose type is
that of the primary key of the
referenced entity as described in
Section 2.4.1. Entities whose primary
keys use types other than these will
not be portable.
If generated primary
keys are used,only integral types
will be portable. If @H_502_6@java.util.Date
is used as a primary key field or
property,the temporal type should be
specified as @H_502_6@DATE.

换句话说,如果有解决方案,它将是提供者特定的.

I’m really not sure how to go about fixing this… anyone have any ideas?

您需要配置EL以进行自定义排序并提供自定义序列生成器.有关完整示例,请参阅EclipseLink/Examples/JPA/CustomSequencing(使用UUID生成器).

猜你在找的Java相关文章