Search code examples
springtype-conversionspring-dataspring-data-jdbc

Spring Data JDBC custom query parameter converter


I am trying to add a custom query to a Spring Data JDBC CrudRepository to allow finding entities by an alternate natural key. The entity has an ID which is in this case a Long, and a natural key, that is of type Reference (underlying type is UUID).

I have created and registered custom converters from Reference to UUID and vice versa, and would like to use them when finding entities by Reference. Conversion works when fetching and storing entities to and from the database (Postgres 12.2).

What I couldn't manage to do is to define a custom method that finds the entity by its Reference.

This is similar to my situation:

public interface OrderRepository implements CrudRepository<Order, Long> {

    @Query("select o from Order o where o.reference = :reference")
    Optional<Order> findByReference(@Param("reference") Order.Reference reference);
}

Can this be done in this way? I am using the latest version of Spring Data JDBC (1.1.6). I would like to avoid having a query that accepts the underlying type (UUID in this case).

If this can't be done by using a custom Query, what are the available options? I have considered maybe using MyBatis with Spring Data JDBC?


Solution

  • This is a known issue, which got implemented with 2.0 M3 which is available from Springs Milestone repository. Please give it a try.

    Note: 2.0 M3 introduces Dialect but proper automatic detection only comes with 2.0 RC1` which is due to be released today 2020-03-31. You may wait for that to save you some headaches