Can JPA be convinced of conversion between UUID and strings?

I have a Java object with a field that is a UUID. I would like for me to be able to store this object in a database in an obvious way; however, the base mapping will use Java serialization to write it, while I want the UUID to be present in its explicit string form. Is there a way to provide a UAID ↔ String to JPA converter for this field that will be used when reading and writing so that I can handle this type normally?

+4
source share
3 answers

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 
+1
source

JPA 2.0 does not provide a general way to do this, except for creating separate getters / setters for different representations of the same field.

Depending on your JPA provider, you can use implementation-specific methods, for example, Hibernate provides the uuid-char type for this purpose:

 @Type(type = "uuid-char") private UUID uuid; 
+4
source

You can annotate your UUID @Transient property and at the same time provide its constant representation based on String.

During @PrePersist , @PreUpdate or @PostLoad you install this String-based view based on the UUID or (if it is loaded from the database) re-create the UUID from the line,

+3
source

Source: https://habr.com/ru/post/1385537/


All Articles