How can I use a custom ID conversion with DomainClassConverter?

风格不统一 提交于 2019-12-25 11:47:32

问题


I have a SQL database where primary keys are UUIDs, but the canonical string representation of a UUID is very long, and I would like to use a shortened version (Base58) in my URLs. Spring Data's DomainClassConverter will convert MVC request parameters or path variables into domain objects, but I want to be able to modify the resolved ID before it's passed to the repository.

The default SpringDataWebConfiguration creates a DomainClassConverter using a FormattingConversionService supplied by the context, which presumably is not safe to arbitrarily mangle. Adding an annotation to the method parameters would potentially disambiguate the interpretation, but this would both have to be replicated all over the place and not work with external controllers such as Spring Data REST. The behavior of delegating the (String parameter->ID) conversion to the conversion service is hard-wired in a private inner class, so I can't modify it there.

Is there any non-invasive way to intercept the parameter and transform it before it's passed to the RepositoryInvoker?


回答1:


easiest is if you create your own Formatter

like:

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 your application context:

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

@EnableSpringDataWebSupport is used to bring a lot of beans into the context, see its javadoc - it's very informative

best



来源:https://stackoverflow.com/questions/33459036/how-can-i-use-a-custom-id-conversion-with-domainclassconverter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!