使用 NamedParameterJdbcTemplate 调用 DB2 时,我收到以下异常:
例外:
org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'Gender' for property 'gender'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [Gender] for property 'gender': no matching editors or conversion strategy found
话虽如此,我试图注册一个性别格式化程序,以及 GenderToString 和 StringToGender 转换器。Formatter 和 Converters 似乎都不起作用。
顺便说一句,我使用带有注释的 java 配置,而不是 XML 配置。所以,我使用一个带有 @Configuration 注释的自定义类来注册这些,它扩展了 WebMvcConfigurerAdapter。此外,在往返 JSP 和 Controller 时,这两种方法都可以正常工作。不知何故,当 Spring 处理我的 DB2 查询时,我觉得我遗漏了一些东西。
网络配置:
@Configuration
@EnableWebMvc // This replaces <mvc:annotation-driven />
@NoTrace
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
private GenderFormatter genderFormatter;
@Autowired
private GenderToStringConverter genderToStringConverter;
@Autowired
private StringToGenderConverter stringToGenderConverter;
@Override
public void addFormatters(final FormatterRegistry registry) {
registry.addFormatter(this.genderFormatter);
registry.addConverter(this.genderToStringConverter);
registry.addConverter(this.stringToGenderConverter);
}
}
道:
@Repository
public class PersonDAO {
public Person retrieve(final int id) {
final MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("id", id);
try {
return this.namedParameterJdbcTemplate.queryForObject(
RETRIEVE_PRIMARY_INSURED,
paramSource,
new BeanPropertyRowMapper<Person>(Person.class));
} catch (final RuntimeException e) {
LOGGER.error("RuntimeException: ", e);
throw e;
}
}
}
public class Person {
private int id;
private Name name = new PersonName();
private Age age;
private Gender gender;
// getters and setters
}