Persisting UUID in PostgreSQL using JPA
The PostgreSQL JDBC driver has chosen an unfortunately way to represent non-JDBC-standard type codes. They simply map all of them to Types.OTHER. Long story short, you need to enable a special Hibernate type mapping for handling UUID mappings (to columns of the postgres-specific uuid datatype):
@Id@Column(name = "customer_id")@org.hibernate.annotations.Type(type="org.hibernate.type.PostgresUUIDType")private UUID id;
or more succinctly:
@Id@Column(name = "customer_id")@org.hibernate.annotations.Type(type="pg-uuid")private UUID id;
Another (better) option is to register org.hibernate.type.PostgresUUIDType as the default Hibernate type mapping for all attributes exposed as java.util.UUID. That is covered in the documentation @ http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html/ch06.html#types-registry
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")
.
To have it working with Hibernate 5.1.x, you can follow Steve Ebersole comment here
@Id@GeneratedValue@Column( columnDefinition = "uuid", updatable = false )public UUID getId() { return id;}