【问题标题】:Spring Boot 2.0.0M2 Thymeleaf 3 failed to convert fieldSpring Boot 2.0.0M2 Thymeleaf 3 无法转换字段
【发布时间】:2017-07-03 17:28:39
【问题描述】:

升级到 spring-boot-2-m2 (thymeleaf 3) 后,我收到与 JPA 关系对应的字段的转换失败错误。

Failed to convert from type [@javax.persistence.ManyToOne @javax.persistence.JoinColumn com.pps2....entities.FormType] to type [java.lang.String] for value 'com.pps2.....FormType@819841af'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.util.Optional<?>] to type [java.lang.String]

JPA 实体

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id_form_type")
private FormType type;

public FormType getType() {
    return type;
}

模板中的代码是:

&lt;select th:field="*{type}" class="col-xs-12"&gt;

抛出类似的失败转换错误。

当然,直接引用时它可以工作,但在这种情况下,它会破坏项目中的许多模板。并将name 生成为type.id 而不是type

工作示例 &lt;select th:field="*{type.id}" class="col-xs-12"&gt;

问题 - 他们为什么要更改 API?有没有办法在不重新检查所有模板的情况下解决它(例如编写转换器?)?

【问题讨论】:

  • 为什么说“Thymeleaf 转换失败”,当它是 Spring 时例外?如果是这种情况,JPA 与转换问题有什么关系?也就是调试问题出在这 3 位软件的地方
  • 感谢我对 Spring 环境很陌生。

标签: spring jpa thymeleaf


【解决方案1】:

解决方案是编写自己的Optional&lt;T&gt; to String 转换器。我不知道为什么它被排除在 Spring Boot 2 M2

之外

转换器代码

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;

@Component
final class OptionalToString implements Converter<Optional<?>, String> {

    public String convert(Optional<?> source) {
        return Objects.toString(source.get(),"");
    }
}

另一种选择

是直接指定列(如id

工作示例&lt;select th:field="*{type.id}" class="col-xs-12"&gt;

【讨论】:

  • 我也必须做同样的事情。另外,我认为如果您也将问题中的“工作示例”也包含在答案中会很有帮助,因为它也是迁移到 spring 5 + thymeleaf 的人的可能解决方法之一
猜你喜欢
  • 1970-01-01
  • 2018-11-15
  • 2019-02-26
  • 2019-06-11
  • 1970-01-01
  • 2019-03-25
  • 2016-02-05
  • 1970-01-01
  • 2017-06-23
相关资源
最近更新 更多