如何在使用NamedParameterJdbcTemplate时转换枚举?

时间:2012-09-07 19:40:55

标签: java spring jdbc jdbctemplate

  

可能重复:
  registering converter for property in BeanPropertyRowMapper

使用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

话虽如此,我试图注册Gender Formatter,GenderToString和StringToGender转换器。 Formatter和Converters都不起作用。

顺便说一句,我使用带有注释的java-configuration而不是XML配置。所以,我正在使用标记有@Configuration注释的自定义类来注册这些注释,该注释扩展了WebMvcConfigurerAdapter。此外,当进出JSP和Controller时,这两种方法都可以正常工作。不知何故,当我处理我的DB2查询时,我觉得我错过了一些东西。

WebConfig:

@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);
    }
}

DAO:

@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
}

0 个答案:

没有答案