Chris Lercher评论了Note: Starting from JPA 2.1, a @Convert annotation can be used with an AttributeConverter.
这种方法运行良好,并且与任何JPA提供程序兼容,而@Type(type =“uuid-char”)是提供程序特定的.
此外,autoApply = true应用于每个实体的每个字段,因此不需要在每个实体中注释每个字段.请参阅文档here并查看以下示例:
转换器类
@Converter(autoApply = true)
public class UuidConverter implements AttributeConverter {
@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);
}
}
实体
@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();
//.....
}
这就是它在数据库中的样子
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