【问题标题】:Using RowMapper for LocalDate为 LocalDate 使用 RowMapper
【发布时间】:2022-01-18 13:00:53
【问题描述】:

我有一个类 RowMapperFactory 可以特别返回 Employee

new Employee(
                            new BigInteger("7499"),
                            new FullName("JOHN", "ALLEN", "MARIA"),
                            Position.SALESMAN,
                            LocalDate.of(1981, 2, 20),
                            new BigDecimal("1600")
                    )

但我想创建一个通用表单。对于new BigIntegernew FullNamePositionnew BigDecimal 我做到了,但是对于LocalDate,如何做到这一点。 LocalDate 必须从列 hired 中获取日期。我试试 LocalDate.from((TemporalAccessor) resultSet.getDate("hired")),但写成hired column not found。如何解决?

public class RowMapperFactory {

    public RowMapper<Employee> employeeRowMapper() {
        return new RowMapper<Employee>() {
            @Override
            public Employee mapRow(ResultSet resultSet) throws SQLException {
                return new Employee(
                        new BigInteger(String.valueOf(resultSet.getInt("id"))),
                        new FullName(resultSet.getString("firstname"),resultSet.getString("lastName"),resultSet.getString("middleName") ),
                        Position.valueOf(resultSet.getString("position")),
                        LocalDate.from((TemporalAccessor) resultSet.getDate("hired")),
                        new BigDecimal(resultSet.getInt("salary"))
                );
            }
        };
    }


}

【问题讨论】:

  • 通过检查该列是否存在,以及您是否使用了正确的数据类型
  • 但列存在吗?怎么做
  • '但列存在',而不是根据该错误消息。该问题与映射无关,它专门告诉您:“未找到已雇用的列”
  • 此列包含什么数据类型?你确定是TemporalAccessor?错误消息肯定会告诉您无法找到该列,您可能在其他地方有错字...
  • 此列保存 LocalDate 数据类型格式“1980-12-17”。它不是 TemporalAccessor

标签: java rowmapper


【解决方案1】:

如果 columnName "hired" 不起作用,请尝试使用索引,看看是否可以找到您要查找的此列。

找到后,可以这样以LocalDate格式检索:

 LocalDate date = resultSet.getObject(colIndex, LocalDate.class);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 2021-08-23
    • 2019-05-02
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多