3

我想对对象的主键使用 PostgreSQL uuid 类型。为此,我创建了一个转换器(实现转换器接口)。下面是相关代码:

    @Override
    public void initialize(DatabaseMapping mapping, Session session) {
        final DatabaseField field;
        if (mapping instanceof DirectCollectionMapping) {
            field = ((DirectCollectionMapping) mapping).getDirectField();
        } else {
            field = mapping.getField();
        }

        field.setSqlType(Types.OTHER);
        field.setTypeName("uuid");
        field.setColumnDefinition("UUID");
    }

然后我用下面的注释注释了相关的实体 X:

@Converter(name="uuidConverter",converterCalss=UUIDConverter.class)
@Convert("uuidConverter")
@Id
public UUID getId()
{
    return id;
}

问题是我有另一个类(Y),它具有以下定义:

@ManyToOne(targetEntity = X.class)
@JoinColumn(name = "x_id")
public X getX();

尽管 EclipseLink 按预期创建了表,但它在尝试插入 Y 类型的对象时会向数据库发送一个字符串。 Postgres 返回以下错误消息:

column "id" is of type uuid but expression is of type character varying at character

任何解决方案/解决方法将不胜感激。

4

6 回答 6

2

我对 EclipseLink JPA + Postgresql + UUID 作为主键有同样的问题。

为了解决这个问题,我合并了来自 Github 和以下链接的代码: https ://forums.oracle.com/forums/thread.jspa?messageID=4584157

下面的 UUIDConverter 代码对我有用,尽管代码肯定不是最好的。

public void initialize(DatabaseMapping ARGMapping, Session ARGSession)
{
    final DatabaseField Field;
    if (ARGMapping instanceof DirectCollectionMapping)
    {
        Field = ((DirectCollectionMapping) ARGMapping).getDirectField();
    }
    else
    {
        Field = ARGMapping.getField();
    }
    Field.setSqlType(Types.OTHER);
    Field.setTypeName("uuid");
    Field.setColumnDefinition("UUID");

    for (DatabaseMapping m : ARGMapping.getDescriptor().getMappings())
    {
        assert OneToOneMapping.class.isAssignableFrom(ManyToOneMapping.class);
        if (m instanceof OneToOneMapping)
        {
            for (DatabaseField field : ((OneToOneMapping) m).getForeignKeyFields())
            {
                field.setSqlType(Types.OTHER);
                field.setColumnDefinition("UUID");
                field.setTypeName("uuid");
            }
        }
    }
}
于 2013-02-26T08:54:22.370 回答
1

尝试在初始化方法中检查映射的 fieldClassification 是什么。它可能会以某种方式获取 String.class,请尝试将其设置为 Object.class。

或者,field.setType(Object.class)

于 2012-11-12T15:25:59.413 回答
1

我在使用 EclipseLink JPA 2.1 + Postgresql + UUID 作为主键时遇到了一些问题,但我找到了不同的解决方案。我采用了 AttributeConverter,但我遇到了 EclipseLink 实现的问题,我用这段代码解决了这个问题:

@javax.persistence.Converter(autoApply = true)
public class PostgresUuidConverter implements AttributeConverter<UUID, Object> {        

    @Override
    public Object convertToDatabaseColumn(UUID uuid) {
        PostgresUuid object = new PostgresUuid();
        object.setType("uuid");
        try {
            if (uuid == null) {
                object.setValue(null);
            } else {
                object.setValue(uuid.toString());
            }
        } catch (SQLException e) {
            throw new IllegalArgumentException("Error when creating Postgres uuid", e);
        }
        return object;
    }

    @Override
    public UUID convertToEntityAttribute(Object dbData) {
        if (dbData instanceof String) {
            return UUID.fromString(dbData.toString());
        } else {    
            return (UUID) dbData;
        }
    }

}


public class PostgresUuid extends PGobject implements Comparable<Object> {

    private static final long serialVersionUID = 1L;

    @Override
    public int compareTo(Object arg0) {
        return 0;
    }

}

正如我在这篇文章中详细解释的那样http://blog-ungarida.rhcloud.com/persisting-uuid-in-postgresql-using-jpa-eclipselink/

于 2014-12-13T15:15:02.260 回答
0

EclipseLink 的通用 UUIDConverter(不仅是 PostgreSQL)

代码:

import java.nio.ByteBuffer;
import java.util.UUID;

import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.DirectCollectionMapping;
import org.eclipse.persistence.mappings.converters.Converter;
import org.eclipse.persistence.sessions.Session;

public class UUIDConverter implements Converter {

    private Boolean isUUIDasByteArray = true;

    @Override
    public Object convertObjectValueToDataValue(Object objectValue,
                                                Session session) {
        if (isUUIDasByteArray) {
            UUID uuid = (UUID)objectValue;
            if (uuid == null) return null;
            byte[] buffer = new byte[16];
            ByteBuffer bb = ByteBuffer.wrap(buffer);
            bb.putLong(uuid.getMostSignificantBits());
            bb.putLong(uuid.getLeastSignificantBits());
            return buffer;
        }
        return objectValue;
    }

    @Override
    public UUID convertDataValueToObjectValue(Object dataValue,
                                              Session session) {
        if (isUUIDasByteArray) {
            byte[] bytes = (byte[])dataValue;
            if (bytes == null) return null;
            ByteBuffer bb = ByteBuffer.wrap(bytes);
            long high = bb.getLong();
            long low = bb.getLong();
            return new UUID(high, low);
        }
        return (UUID) dataValue;
    }

    @Override
    public boolean isMutable() {
        return true;
    }

    @Override
    public void initialize(DatabaseMapping mapping, Session session) {
        final DatabaseField field;
        if (mapping instanceof DirectCollectionMapping) {
            // handle @ElementCollection...
            field = ((DirectCollectionMapping) mapping).getDirectField();
        } else {
            field = mapping.getField();
        }

        if (session != null && session.getLogin()!= null && session.getLogin().getPlatform() != null) {
            String platform = session.getLogin().getPlatform().getClass().getSimpleName();

            if (platform.equals("PostgreSQLPlatform")) {
                field.setSqlType(java.sql.Types.OTHER);
                field.setTypeName("java.util.UUID");
                field.setColumnDefinition("UUID");
                isUUIDasByteArray = false;
            } else if (platform.equals("H2Platform")) {
                field.setColumnDefinition("UUID");
            } else if (platform.equals("OraclePlatform")) {
                field.setColumnDefinition("RAW(16)");
            } else if (platform.equals("MySQLPlatform")) {
                field.setColumnDefinition("BINARY(16)");
            } else if (platform.equals("SQLServerPlatform")) {
                field.setColumnDefinition("UNIQUEIDENTIFIER");
            }
        }

    }
}
于 2017-11-11T20:36:58.760 回答
0

你不需要转换。在实体中使用此列定义。您需要先注册 uuid 扩展。这适用于 Postgres 10 和 Wildfly 10.1

@Column(name = "UUID", nullable=false, insertable = false, columnDefinition="uuid DEFAULT uuid_generate_v4()")
private String uuid;
于 2018-02-27T22:54:36.600 回答
0

EclipseLink 和 PostgresQL 之间似乎存在错误/不兼容。如果你只是使用 UUID 作为主键,你应该没问题。但是如果你有一个可以为空的 UUID 列,并且你尝试在其中存储 null,你会得到报告的错误:

column "whatever" is of type uuid but expression is of type character varying

请参阅:https ://bugs.eclipse.org/bugs/show_bug.cgi?id=538138 (如果有时间,请登录并投票!)

那个错误报告证明对我非常有用。特别是论坛主题的链接:

https://www.eclipse.org/forums/index.php?t=msg&th=1073632&goto=1719530&#msg_1719530

我在 SO 和网络上的其他地方尝试了各种解决方案。唯一对我有用的是大卫惠勒在那里发布的。具体来说,在数据库中创建一个转换 from character varyingto 。uuid

请注意,您必须是用户 postgres 才能创建演员表:

$ sudo su - postgres
$ psql <your database name>

# drop cast if exists (character varying as uuid);
# create or replace function uuid(_text character varying) returns uuid language sql as 'select uuid_in(_text::cstring)';
# create cast (character varying as uuid) with function uuid(character varying) as assignment;

为了完整起见,这里是我使用的其余部分(以防有帮助)

我所有的实体(具有 UUID 主键)都扩展了一个名为EntityBase

package com.example.entity;

import java.io.Serializable;
import java.util.UUID;

import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

import org.eclipse.persistence.annotations.Convert;
import org.eclipse.persistence.annotations.Converter;

import com.example.converter.UUIDTypeConverter;

@MappedSuperclass
@Converter(name="uuidConverter", converterClass=UUIDTypeConverter.class)
public class EntityBase implements Serializable, Cloneable
{
   private static final long serialVersionUID = 1L;

   @Id
   @Convert("uuidConverter")
   private UUID  id;


   public EntityBase() {
      this.id = UUID.randomUUID();
   }

   @Override
   public int hashCode() {
      return id.hashCode();
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null)
         return false;
      if (!(obj instanceof EntityBase)) {
         return false;
      }
      EntityBase other = (EntityBase) obj;
      return getId().equals(other.getId());
   }

   public UUID getId()
   {
      return this.id;
   }

   public void setId(UUID id)
   {
      this.id = id;
   }
}

UUID 转换器类如下所示:

package com.example.converter;

import java.sql.Types;
import java.util.UUID;

import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.converters.Converter;
import org.eclipse.persistence.sessions.Session;


public class UUIDTypeConverter implements Converter
{
   @Override
   public UUID convertObjectValueToDataValue(Object objectValue, Session session)
   {
      return (UUID) objectValue;
   }


   @Override
   public UUID convertDataValueToObjectValue(Object dataValue, Session session)
   {
      return (UUID) dataValue;
   }


   @Override
   public boolean isMutable()
   {
      return true;
   }


   @Override
   public void initialize(DatabaseMapping mapping, Session session)
   {
      DatabaseField field = mapping.getField();
      field.setSqlType(Types.OTHER);
      field.setTypeName("java.util.UUID");
      field.setColumnDefinition("UUID");
   }
}

如果您的实体的 UUID 列不是主键,则可以按如下方式对其进行注释:

import org.eclipse.persistence.annotations.Convert
import org.eclipse.persistence.annotations.Converter;

@Entity
@Converter(name="uuidConverter", converterClass=UUIDTypeConverter.class)
public class BillingEvent extends EntityBase
{

   @Convert("uuidConverter")
   private UUID  entityId;

}

请注意,如果该实体具有使用标准javax.persistence.convert注释的其他列,则需要区分这两个Convert注释以避免编译错误。

例如:

import javax.persistence.Convert;
import org.eclipse.persistence.annotations.Converter;

@Entity
@Converter(name="uuidConverter", converterClass=UUIDTypeConverter.class)
public class BillingEvent extends EntityBase
{

   @org.eclipse.persistence.annotations.Convert("uuidConverter")
   private UUID  entityId;

   @Convert(converter = JSR310InstantTypeConverter.class)
   private Instant     createdOn;
}

我希望这可以节省其他人一些时间。祝你好运!

于 2020-04-18T14:49:51.187 回答