Friday, January 24, 2014

Accessing Postgres UUID with JPA

http://stackoverflow.com/questions/11284359/persisting-uuid-in-postgresql-using-jpa

JPA 2.1 provides a very easy way to use the PostgreSQL uuid column type and java.util.UUID as the type of the corresponding entity field:
@javax.persistence.Converter(autoApply = true)
public class PostgresUuidConverter implements AttributeConverter<UUID, UUID> {

    @Override
    public UUID convertToDatabaseColumn(UUID attribute) {
        return attribute;
    }

    @Override
    public UUID convertToEntityAttribute(UUID dbData) {
        return dbData;
    }

}
Just add this class to your persistence configuration and annotate UUID fields with@Column(columnDefinition="uuid").

2 comments:

  1. Not a correct solution. Results in exception at runtime, 'expression is of type bytea[], requires UUID'...

    This simple 'solution' is all over the net, and is misleading.

    ReplyDelete
  2. I agree with SleepsOnGrates. I get the same error.

    ReplyDelete