JPA 2.1 and UUID
Recently I came over to map a table in a Postgres Database that contains a UUID Column. With JPA 2.1 there is a very simple way to map this column to the java.util.UUID-Field in the entity:
At first you need a AttributeConverter:
/**
* Converter for use with UUID and Postgres
*/
@Converter(autoApply = true)
public class UuidConverter implements AttributeConverter<UUID, UUID> {
/**
* Convert entity field to db column value
*
* @param attribute field
* @return UUID of entity
*/
@Override
public UUID convertToDatabaseColumn(UUID attribute) {
return attribute;
}
/**
* Convert db column value to entity field
*
* @param dbData column
* @return UUID of entity
*/
@Override
public UUID convertToEntityAttribute(UUID dbData) {
return dbData;
}
}
And now just add this Converter to your Entity-Fields with the @Column-Annotation:
@Column(name = "guid", columnDefinition = "UUID", updatable = false, insertable = false)
private UUID uuid;