2017-07-03 36 views
0

在升级到弹簧引导2-m2(thymeleaf 3)后,对于与JPA关系对应的字段,我收到了失败的转换错误。Spring Boot 2.0.0M2 Thymeleaf 3无法转换字段

Failed to convert from type [@javax.persistence.ManyToOne @javax.persistence.JoinColumn com.pps2....entities.FormType] to type [java.lang.String] for value '[email protected]'; 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; 
} 

的模板代码为:

<select th:field="*{type}" class="col-xs-12">

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

当然,当直接引用它的工作,但在这种情况下,它打破了项目中的很多模板。并生成name作为type.id而不是type

工作实例 <select th:field="*{type.id}" class="col-xs-12">

问题 - 为什么他们改变了API?有没有办法解决它而不重新检查所有模板(例如写入转换器?)?

+0

为什么在除了Spring之外说“Thymeleaf未能转换”?如果是这样的话,JPA是如何处理转换问题的?又名调试,其中的问题是那些3位软件 –

+0

谢谢我对Spring环境非常新鲜。 – BlackTea

回答

1

解决方案是编写自己的Optional<T> to String转换器。我不知道为什么有人从春季启动排除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

工作示例<select th:field="*{type.id}" class="col-xs-12">

+0

我也必须在我的情况下也做同样的事情。另外,我认为如果你在答案中也包含了你的“工作示例”这个问题,那么这将会对你有所帮助,因为它也是人们迁移到春季的一个可能的解决方案5 + thymeleaf – Ranjeet

+0

谢谢,更新了答案 – BlackTea

相关问题