Chris Lercher commented Note: Starting with JPA 2.1, @Convert annotation can be used with an AttributeConverter<UUID, String>
.
This approach works well and is compatible with any JPA provider, while @Type(type = "uuid-char")
is a specific provider. In addition, when autoApply=true
is applied to each field of each entity, so there is no need to comment on each field in each object. See the documentation here and check out the example below:
Converter class
@Converter(autoApply = true) public class UuidConverter implements AttributeConverter<UUID, String> { @Override public String convertToDatabaseColumn(final UUID entityValue) { return ofNullable(entityValue) .map(entityUuid -> entityUuid.toString()) .orElse(null); } @Override public UUID convertToEntityAttribute(final String databaseValue) { return ofNullable(databaseValue) .map(databaseUuid -> UUID.fromString(databaseUuid)) .orElse(null); } }
An object
@Entity public class Customer implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @Column private String name; @Column(nullable = false, unique = true, updatable = false, columnDefinition="CHAR(36)") private UUID customerId = randomUUID();
And this is how it looks in the database
TABLE customer ID BIGINT(19) NO PRI (NEXT VALUE FOR SYSTEM_SEQUENCE_5D3) NAME VARCHAR(255) YES NULL CUSTOMER_ID VARCHAR(36) NO UNI NULL
source share