首页 > 解决方案 > 如何使用不同类型的值向 java new Object[] 添加动态值

问题描述

我目前正在使用如下这种语法工作正常

Object[] oParams = new Object[] {
    Integer.valueOf(this.userId),
    Date.valueOf(this.startDate), 
    Date.valueOf(this.endDate) 
};
jdbcTemplate.queryForList(sql, oParams);

如果它在PHP我们可以简单地添加索引但是在java中下面的语法是抛出错误

oParams[3] = Integer.valueOf(this.userId)

如果我添加如下值,

List<Object> oParams = new ArrayList<Object>();
oParams.add(Integer.valueOf(this.userId));
oParams.add(Date.valueOf(this.startDate));
oParams.add(Date.valueOf(this.endDate));
jdbcTemplate.queryForList(sql, oParams);

它导致以下错误,

org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of java.util.ArrayList. Use setObject() with an explicit Types value to specify the type to use. at org.postgresql.jdbc.PgPreparedStatement.setObject(PgPreparedStatement.java:949)

提前致谢。

标签: javaspringspring-boot

解决方案


好吧..如果你真的需要一个Object[]你可以转换你的List<Object>using .toArray()

List<Object> oParams = new ArrayList<>();
oParams.add(Integer.valueOf(this.userId));
oParams.add(Date.valueOf(this.startDate));
oParams.add(Date.valueOf(this.endDate));
jdbcTemplate.queryForList(sql, oParams.toArray());

推荐阅读