0
votes

There are any way to save some field of entity as Json with spring-data-r2dbc?

Example:

@Table("A")
class A {
  @Id
  var id: String = "1"
  var some: MutableMap<String, String> = mutableMapOf()
}

And table:

create table A (
   id varchar(255) not null primary key,
   some jsonb
)

I've looked at Convertors of Spring data R2DBC, but It is necessery to write separate convertor for every class. Does it possible to generate converters to Json dynamically in runtime for all classes inherited from some special interface or annotated by specific annotation?

Thanks!

1

1 Answers

0
votes
annotation class StoreJson

...


@Bean
fun converters() = R2dbcCustomConversions(
     Reflections().getTypesAnnotatedWith(StoreJson::class.java).map { clz ->
        mutableListOf(
            @WritingConverter
            object : GenericConverter {
                override fun getConvertibleTypes() = setOf(GenericConverter.ConvertiblePair(clz, Json::class.java))
                override fun convert(source: Any?, p1: TypeDescriptor, p2: TypeDescriptor) =
                    Json.of(objectMapper.writeValueAsString(source))
            },
            @ReadingConverter
            object : GenericConverter {
                override fun getConvertibleTypes() = setOf(GenericConverter.ConvertiblePair(Json::class.java, clz))
                override fun convert(source: Any?, p1: TypeDescriptor, p2: TypeDescriptor) =
                    objectMapper.readValue((source as Json).asString(), clz)
            }
        )
    }.flatten().toMutableList()
)