简体   繁体   English

Spring JDBC ResultSetMetaData“ getColumnName()”方法返回一个空字符串

[英]Spring JDBC ResultSetMetaData “getColumnName()” method returns an empty string

I have the following section of code to implement a drop-down menu. 我有以下代码部分来实现下拉菜单。 Based on the two parameters selected from the menu, I run the corresponding query by replacing the selected column with the mapped column name. 基于从菜单中选择的两个参数,我通过将所选列替换为映射的列名来运行相应的查询。

String sql = "SELECT ?, ? FROM <table_name>";

ArrayList<Some_POJO> res = this.jdbcTemplate.query(sql, new ResultSetExtractor<Some_POJO>()
    {//logic goes here.},
    user_inputs_as_object_array);

Now, in the logic section, I'm using the following command to map the returned values: 现在,在逻辑部分中,我使用以下命令映射返回的值:

while(rs.next()) {
    Some_POJO = new SOME_POJO();
    Some_POJO.setParam1(rs.getString("SOME_COLUMN_NAME")); //ERROR
}

Now, the marked line fails when I refer to column by name. 现在,当我按名称引用列时,标记行将失败。 But what is surprising is, the following workaround works: 但是令人惊讶的是,以下解决方法有效:

while(rs.next()) {
    Some_POJO = new SOME_POJO();
    int i = 1;
    Some_POJO.setParam1(rs.getString(i)); //Works(?!)
}

I tried to modify the JDBC template call to return the ResultSetMetaData object instead of an ArrayList of Some_POJO: 我试图修改JDBC模板调用以返回ResultSetMetaData对象而不是Some_POJO的ArrayList:

String sql = "SELECT ?, ? FROM <table_name>";

ResultSetMetaData res = this.jdbcTemplate.query(sql, new ResultSetExtractor<ResultSetMetaData>()
    {//extractData now returns rs.getMetaData()},
    user_inputs_as_object_array);

try
    {
        System.out.println("Column cout: " + res.getColumnCount());
        for(int i = 1; i <= res.getColumnCount(); i++)
            System.out.println("Label: " + res.getColumnLabel(i) +  "\nName: " + res.getColumnName(i));
    }
    catch(SQLException sqle)

Only to get: 只能得到:

Column cout: 2
Label: :1
Name: 
Label: :2
Name:

Could someone please shed some light into what is happening and (except for suggestions suggesting a complete redesign) what would be the most optimal way to achieve the expected functionality? 有人可以说明正在发生的事情吗(建议完全重新设计的建议除外),什么是实现预期功能的最佳方法? I would prefer not to use column indexes since order changes would break the functionality. 我宁愿不使用列索引,因为顺序更改会破坏功能。

Just for refactoring code, get values as: 仅用于重构代码,将值获取为:

    ArrayList result = new ArrayList(0);
    result.addAll(this.jdbcTemplate.query(sql, (RowMapper) (rs, rowNum) -> {
        POJO out = new POJO();
        out.setProperty1(rs.getString("prop1"));
        out.setProperty2(rs.getString("prop2"));
        ...
        return out;
    }));

For me it works fine, passing field name in method, don't think that there are some troubles with spring jdbc. 对我来说,它可以正常工作,在方法中传递字段名称,不要认为spring jdbc会有麻烦。 Maybe is something wrong in your sql query. 也许在您的SQL查询中有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM