How can I use custom ID translation with DomainClassConverter?

I have an SQL database where the primary keys are the UUIDs, but the canonical string representation of the UUIDs is very long, and I would like to use the shortened version (Base58) in my URLs. Spring DomainClassConverter data converts MVC request parameters or path variables to domain objects, but I want to be able to change the allowed ID before passing it to the repository.

By default, SpringDataWebConfiguration creates a DomainClassConverter using the FormattingConversionService provided by a context that is supposedly unsafe for arbitrary mutilation. Adding annotation to the method parameters could potentially lead to an inconsistent interpretation, but this should have been replicated everywhere and not work with external controllers such as Spring Data REST. The behavior of delegating a conversion ( String parameter → ID) to the conversion service is tightly coupled to the inner inner class, so I cannot change it there.

Is there any non-invasive way to intercept a parameter and convert it before it moves to RepositoryInvoker ?

0
java spring spring-data spring-data-commons type-conversion
source share
1 answer

easiest if you create your own formatter

as:

 public class UserFormatter implements Formatter<User> { @Autowired UserRepository userRepository; @Override public User parse(String text, Locale locale) throws ParseException { return userRepository.findOneByUsername(text); } @Override public String print(User user, Locale locale) { return user.getUsername(); } } 

then register it in the context of your application:

 @Configuration @EnableSpringDataWebSupport public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addFormatters(FormatterRegistry registry) { registry.addFormatter(userFormatter()); } @Bean public UserFormatter userFormatter() { return new UserFormatter(); } } 

@EnableSpringDataWebSupport used to transfer a large number of beans to the context, see its javadoc is very informative

it's better

+1
source share

All Articles