我有一个具有 UUID 列的实体(它不是主键)。我正在使用 Postgres 和 hibernate。我对此专栏的类型是https://www.postgresql.org/docs/9.1/static/datatype-uuid.html https://www.postgresql.org/docs/9.1/static/datatype-uuid.html .
If I do
@Type(type = "pg-uuid")
@Column(name = "uuid", unique = true, updatable = false)
private UUID myUuid;
一切都很好。但是,我不希望此列成为 UUID,而只是为了它而希望它成为 Java 字符串。当我更改为
@Type(type = "pg-uuid")
@Column(name = "uuid", unique = true, updatable = false)
private String myUuid;
I get
ClassCastException: java.lang.String cannot be cast to java.util.UUID
当我做
@Column(name = "uuid", unique = true, updatable = false)
private String myUuid;
I get
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();
}
}
I get
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();
}
}
I get
PSQLException: ERROR: column "uuid" is of type uuid but expression is
of type bytea
Hint: You will need to rewrite or cast the expression.
我在这里缺少什么?我将非常感谢帮助。