spring-projects / spring-data-r2dbc

Provide support to increase developer productivity in Java when using Reactive Relational Database Connectivity. Uses familiar Spring concepts such as a DatabaseClient for core API usage and lightweight repository style data access.
Apache License 2.0
708 stars 132 forks source link

Custom converter in R2dbcEntityOperations breaks nested mappings #850

Closed SledgeHammer01 closed 7 months ago

SledgeHammer01 commented 7 months ago

I'm using the MySQL Sakilla DB (a sample database they provide). My resulting JSON looks like:

  {
    "filmId": 1,
    "title": "Academy Dinosaur",
    "description": "An epic drama of a feminist and a mad scientist who must battle a teacher in the canadian rockies",
    "releaseYear": 2006,
    "rating": "PG",
    "actors": [
      {
        "firstName": "Penelope",
        "lastName": "Guiness"
      }
    ]
  }

I'm connecting to multiple DBs, so I use R2dbcEntityOperations. I need to do some mapping on the rating field, so I added a custom converter. Now the resulting JSON is:

  {
    "filmId": 1,
    "title": "Academy Dinosaur",
    "description": "An epic drama of a feminist and a mad scientist who must battle a teacher in the canadian rockies",
    "releaseYear": 2006,
    "rating": "PG",
    "actors": []
  }

My code looks like this:

  @Bean
  public R2dbcEntityOperations filmsEntityOperations(ConnectionFactory filmsConnectionFactory) {
    DatabaseClient databaseClient =
        DatabaseClient.builder().connectionFactory(filmsConnectionFactory).build();

    MappingR2dbcConverter customMappingConverter = new MappingR2dbcConverter(r2dbcMappingContext(), myr2dbcCustomConversions());

    return new R2dbcEntityTemplate(databaseClient, MySqlDialect.INSTANCE, customMappingConverter);
  }

  private R2dbcMappingContext r2dbcMappingContext() {
    R2dbcCustomConversions r2dbcCustomConversions = myr2dbcCustomConversions();
    R2dbcMappingContext context = new R2dbcMappingContext(DefaultNamingStrategy.INSTANCE);
    context.setSimpleTypeHolder(r2dbcCustomConversions.getSimpleTypeHolder());
    return context;
  }

  private R2dbcCustomConversions myr2dbcCustomConversions() {
    Collection<?> converters = Arrays.asList(new RatingConverter2(), new RatingConverter());
    R2dbcCustomConversions conversions = R2dbcCustomConversions.of(MySqlDialect.INSTANCE,converters);
    return conversions;
  }