Postgres UUID和hibernate

时间:2017-07-29 13:24:49

标签: java postgresql hibernate jpa

我有一个具有UUID列的实体(它不是主键)。我正在使用Postgres和hibernate。我对此列的类型为https://www.postgresql.org/docs/9.1/static/datatype-uuid.html

如果我这样做

@Type(type = "pg-uuid")
@Column(name = "uuid", unique = true, updatable = false)
private UUID myUuid;

一切正常。但是,我不希望这个列成为UUID,我希望它只是为了它而成为一个Java String。当我改为

@Type(type = "pg-uuid")
@Column(name = "uuid", unique = true, updatable = false)
private String myUuid;

我得到了

ClassCastException: java.lang.String cannot be cast to java.util.UUID

当我这样做时

@Column(name = "uuid", unique = true, updatable = false)
private String myUuid;

我得到了

PSQLException: ERROR: column "uuid" is of type uuid 
but expression is of type character varying

当我这样做时

@Convert(converter = UUIDAttributeConverter.class)
@Column(name = "uuid", unique = true, updatable = false, columnDefinition = "uuid")
private String uuid;

其中UUIDAttributeConverter是:

@Converter
public class UUIDAttributeConverter implements  
AttributeConverter<String, PGobject> {
  @Override
  public PGobject convertToDatabaseColumn(String uuid) {
    PGobject toInsertUUID = new PGobject();
    toInsertUUID.setType("uuid");
    try {
        toInsertUUID.setValue(UUID.fromString(uuid).toString());
    } catch (SQLException e) {
        throw new IllegalArgumentException();
    }

    return toInsertUUID;
  }

  @Override
  public String convertToEntityAttribute(PGobject dbData) {
    return dbData.toString();
  }
}

我得到了

PSQLException: ERROR: column "uuid" is of type uuid but expression is of type bytea

提示:您需要重写或转换表达式。

当我再次进行转换时,但这次是转换器

@Converter
public class UUIDAttributeConverter implements AttributeConverter<UUID, 
String> {
  @Override
  public UUID convertToEntityAttribute(String s) {
    return UUID.fromString(s);
  }

  @Override
  public String convertToDatabaseColumn(UUID id) {
    return id.toString();
  }
}

我得到了

PSQLException: ERROR: column "uuid" is of type uuid but expression is 
of type bytea
Hint: You will need to rewrite or cast the expression.

我在这里缺少什么?我非常感谢帮助。

0 个答案:

没有答案