Has anyone tried to use a `value class` as a PK fo...
# spring
e
Has anyone tried to use a
value class
as a PK for R2DBC? I wanted to create one to enforce UUID type:
Copy code
@JvmInline
value class UUID(val uuid: java.util.UUID) {
    init {
        require(UuidUtil.getVersion(uuid) == UuidVersion.VERSION_TIME_ORDERED_EPOCH) {
            "UUID must be version 7"
        }
    }

    override fun toString(): String = uuid.toString()

    constructor() : this(UuidCreator.getTimeOrderedEpochPlus1())

    companion object {
        fun fromString(uuid: String): UUID = UUID(java.util.UUID.fromString(uuid))
    }
}
But the repo returns nothing for a
findById
w/ this. Works w/ a regular UUID.
Ended up having to use a regular class instead of value class.
Copy code
@JsonSerialize(using = ToStringSerializer::class)
@JsonDeserialize(using = UUIDv7.Deserializer::class)
class UUIDv7(private val uuid: UUID) {
    init {
        require(UuidUtil.getVersion(uuid) == UuidVersion.VERSION_TIME_ORDERED_EPOCH) {
            "UUID must be version 7"
        }
    }

    constructor() : this(UuidCreator.getTimeOrderedEpochPlus1())

    override fun toString() = uuid.toString()

    override fun equals(other: Any?) = other is UUIDv7 && uuid == other.uuid

    override fun hashCode() = uuid.hashCode()

    companion object {
        fun fromString(uuid: String): UUIDv7 = UUIDv7(UUID.fromString(uuid))
    }

    object ToUUIDConverter : Converter<UUIDv7, UUID> {
        override fun convert(source: UUIDv7) = source.uuid
    }

    object FromUUIDConverter : Converter<UUID, UUIDv7> {
        override fun convert(source: UUID) = UUIDv7(source)
    }

    class Deserializer : FromStringDeserializer<UUIDv7>(UUIDv7::class.java) {
        override fun _deserialize(value: String, ctxt: DeserializationContext) = UUIDv7.fromString(value)
    }
}

@Component
class StringToUUIDv7Converter : Converter<String, UUIDv7> {
    override fun convert(source: String) = UUIDv7.fromString(source)
}
And then register the converters:
Copy code
@Configuration
class R2DBCConfiguration {

    @Bean
    fun r2dbcCustomConversions(connectionFactory: ConnectionFactory) =
            R2dbcCustomConversions.of(
                    DialectResolver.getDialect(connectionFactory),
                    UUIDv7.ToUUIDConverter,
                    UUIDv7.FromUUIDConverter,
            )
}