Search code examples
springspring-bootspring-data-restquerydsl

Change datetime string format in request url when using Spring data rest with QuerydslPredicateExecutor


In my domain class I have a field:

public class Reservation {
    private LocalDateTime created = LocalDateTime.now();

In my repository I want to find only Reservations with some specific date (time doesn't matter):

public interface ReservationRepository extends Repository<Reservation, Long>, QuerydslPredicateExecutor<Reservation>, QuerydslBinderCustomizer<QReservation> {

        bindings.bind(root.created).first((path, value) -> path.between(value.withMinute(0).withHour(0), value.withMinute(0).withHour(0).plusDays(1).minusSeconds(1)));
    }
}

Now it works with this url:

/reservations?created=01/20/16 00:00 AM"

But I want to use this datatime format:

2016-01-20T00:00

As I understood the problem that Spring boot uses RepositoryRestMvcConfiguration.class for autoconfiguration. And by default TemporalAccessorParser.class uses some default DateTimeFormatter. And I want to change it to

DateTimeFormatter ISO_LOCAL_DATE_TIME

Solution

  • If only @DateTimeFormat annotation did not help, try to add to the project a custom Converter:

    public class CustomStringToLocalDateTime implements Converter<String, LocalDateTime> {
    
        @Override
        public LocalDateTime convert(String source) {
            return LocalDateTime.parse(source);
        }
    }
    
    @Configuration
    public class RepoRestConfig extends RepositoryRestConfigurerAdapter {
        @Override
        public void configureConversionService(ConfigurableConversionService conversionService) {
            conversionService.addConverter(String.class, LocalDateTime.class, new CustomStringToLocalDateTime());
            super.configureConversionService(conversionService);
        }
    }
    

    Such an approach works in my project (except I had to convert string representation of date ('yyyy-MM-dd') to Instant (yyyy-MM-ddThh:mm:ssZ)).