4

我正在尝试设置 Spring Data/JPA DomainClassConverter 以自动将(字符串)id 转换为域类本身。

我的项目是使用 Java Config(所以没有 xml)。

在我的 WebConfig 中,我目前有:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new DomainClassConverter<DefaultFormattingConversionService>((DefaultFormattingConversionService) registry));
    }
}

这似乎成功连接了 DomainClassConverter,因为我可以在打印时在转换服务中看到它:

ConversionService converters =
  ..<default converters>..
  org.springframework.data.repository.support.DomainClassConverter@6ea4ce0d, org.springframework.core.convert.support.IdToEntityConverter@5d3f03b, org.springframework.core.convert.support.ObjectToObjectConverter@1d40b47a

但是当提交嵌套表单(带有客户参考的订单)时,客户不会自动转换,因此我得到:

Failed to convert property value of type java.lang.String to required type org.mycomp.domain.Customer for property customer; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.mycomp.domain.Customer] for property customer: no matching editors or conversion strategy found

我想知道我是否在这里做错了什么?

4

2 回答 2

7

DomainClassConverter应该声明为 bean(因为它是ApplicationContextAware),并且它会ConversionService自动注册,因此您不需要手动注册它:

@Bean @Autowired
public DomainClassConverter domainClassConverter(ConversionService cs) {
    return new DomainClassConverter(cs);
}
于 2012-09-14T09:25:11.960 回答
-1

例外情况是告诉您需要一个自定义转换器才能将字符串转换为客户。您必须标记输入并将其映射到客户字段。对于您的所有域类都是如此。

谷歌搜索也将我带到 Spring 论坛中的一个线程:

http://forum.springsource.org/showthread.php?122944-Help-with-DomainClassConverter-configuration

它表明可能存在错误,具体取决于您使用的 Spring 版本。

于 2012-09-14T09:18:08.987 回答