Mapping to JSON Fields with Spring Data R2DBC and Reactive Postgres Driver

Nikola Babić
2 min readOct 31, 2019

--

With the 0.8.0.rc1 release of r2dbc-postgres reactive driver we can now use JSON and JSONB database field types and map them to our custom type properties in entities using spring-data-r2dbc module.

This is extremely useful if we want to store some map with objects that belong to an entity but we do not need/want the extra database table.

Let’s take a look at a simple model class Product:

Part of Product.java file

This class consists of simple fields id, name, and owner_id and one complex field parameters which is map that holds any type of objects. We want to store this map in a JSON database field. We can do this by extending Spring’s Converter interface and providing the mapping logic. We need two implementations, one for writing to database and one for reading from database. Let’s see how both converters look like:

Part of MapToJsonConverter.java file

We are implementing org.springframework.core.convert.converter.Converter interface with parameterized types Map<String, Object> and Json. Former type parameter is used as type of the source object and latter is the destination type. In the overridden convert method we just stringify the map and wrap it as Json class type. Note the WritingConverter annotation which tells Spring to use this converter only when persisting these types in the database.

Part of JsonToMapConverter.java file

The reverse mapping converter just reads the stringified JSON and converts it to Map<String, Object>. The ReadingConverter annotation notifies Spring to use this converter only when reading from database.

Now the only thing left is to connect these converters to our R2DBC configuration. We can do that easily by overriding r2dbcCustomConversions bean:

Part of ReactivePostgresConfig.java file

Finally we can seamlessly read and write products from/to the database using reactive repository:

ProductRepository.java file
Example of usage

In this article we’ve seen how easy it is to plug in converters and serialize complex Java types into JSON fields in the new and exciting word of reactive relational database access. The full source code is available on GitHub.

--

--

Nikola Babić

CEO & Co-founder of software company CODIFICA LLC based in Zagreb, Croatia. Previously independent Java consultant. Reactive programming evangelist.