SQL 问题不是通过 JdbcTemplate 查询 运行

Issue with SQL query not running via JdbcTemplate

我遇到了这个奇怪的问题,其中 sql 查询使用 Oracle Pivot 语法。我可以 运行 在 SqlDeveloper 中毫无问题地进行查询;但是,运行使用 RowMapper 通过 JdbcTemplate 将其设置为关于无效列名的奇怪错误。

org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar ... nested exception is java.sql.SQLException: Invalid column name

SQL 语句:

select * from ( 
    Select stat.SWRHXML_HXPS_CODE  
    FROM Swbhxml xml 
    LEFT JOIN Swrhxml stat ON stat.swrhxml_trans_id = xml.SWBHXML_TRANS_ID 
    WHERE stat.SWRHXML_ACTIVITY_DATE = (
        SELECT MAX(st.SWRHXML_ACTIVITY_DATE) 
        FROM swrhxml st 
        WHERE stat.SWRHXML_TRANS_ID = st.SWRHXML_TRANS_ID)
   ) pivot (count(SWRHXML_HXPS_CODE) 
       for SWRHXML_HXPS_CODE in 
        ('NEW','EXPORT_READY','PENDING_MATCH','MATCHED_ID','PROCESSED','REJECTED'));

行映射器:

public class TranscriptStatusCountRowMapper implements RowMapper {

    @Override
    public Object mapRow(ResultSet rs, int rowNum) throws SQLException {

        TranscriptStatusCounts tsc = new TranscriptStatusCounts();

        tsc.setNewCount(rs.getLong("NEW_RECORDS"));
        tsc.setExportReadyCount(rs.getLong("EXPORT_READY"));
        tsc.setPendingMatchCount(rs.getLong("PENDING_MATCH"));
        tsc.setMatchedIdCount(rs.getLong("MATCHED_ID"));
        tsc.setProcessedCount(rs.getLong("PROCESSED"));
        tsc.setRejectedCount(rs.getLong("REJECTED"));
        return tsc;
    }
}

DAO 调用 class:

@Repository("transcriptCountDao")
public class TranscriptCountDaoImpl extends BaseDaoImpl implements   TranscriptCountDao {

    private static final Logger logger =    Logger.getLogger(TranscriptCountDaoImpl.class);

    @Override
    public TranscriptStatusCounts findTranscriptStatusCount() {
        logger.debug("Getting counts of Transcripts status in system"); 
        String sql =  "...sql posted above..."
        TranscriptStatusCounts tsc = 
            (TranscriptStatusCounts) getJdbcTemplate().queryForObject(sql, new TranscriptStatusCountRowMapper());   
        return tsc;
    }
}

好的...我想通了...

Pivot table 列并没有真正映射到我的行映射器。因此,我将行映射器更改为以下解决问题的方法:

TranscriptStatusCounts tsc = new TranscriptStatusCounts();
    //'NEW','EXPORT_READY','PENDING_MATCH','MATCHED_ID','PROCESSED','REJECTED'
    tsc.setNewCount(rs.getLong(1));
    tsc.setExportReadyCount(rs.getLong(2));
    tsc.setPendingMatchCount(rs.getLong(3));
    tsc.setMatchedIdCount(rs.getLong(4));
    tsc.setProcessedCount(rs.getLong(5));
    tsc.setRejectedCount(rs.getLong(6));
    return tsc;

忘记了sql"Invalid Column Name"错误也可以引用resultSet中用来访问列的名称。因为 PIVOT 查询对它们进行排序,所以我可以只使用列的编号来取回结果。