Do I have to create another RowMapper?

Marcelo Melo :

I'm developing this application to fetch data from a single table from an existing Oracle database.

Here we've got the entity:

public class OrdemDeServicoCount {

    private Long ordensInternas;
    private Long ordensAtrasadas;

    // assume getters and setters
}

The mapper:

public class OrdemMapper implements RowMapper<OrdemDeServicoCount> {

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

        OrdemDeServicoCount ordens = new OrdemDeServicoCount();

        ordens.setOrdensInternas(rs.getLong("ordensInternas"));

//      ordens.setOrdensAtrasadas(rs.getLong("ordensAtrasadas"));

        return ordens;
    }
}

And finally, the DAO:

public class OrdemDAO {

    private JdbcTemplate jdbcTemplate;

    public OrdemDAO(JdbcTemplate jdbcTemplate) {
        super();
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<OrdemDeServicoCount> countOrdensInternasSemEncerrar() {

        String sql = "SELECT COUNT(a.nr_sequencia) AS ordensInternas FROM MAN_ORDEM_SERVICO a "
                + "WHERE a.IE_STATUS_ORDEM IN (1,2) AND a.NR_GRUPO_PLANEJ IN (21)";

        List<OrdemDeServicoCount> ordens = jdbcTemplate.query(sql, new OrdemMapper());

        return ordens;
    }

By the way, you all must know that if I declare uncomment the line ordens.setOrdensInternas(rs.getLong("ordensInternas")); in the mapper, I would get an error, because in my DAO, I'm not using that field.

But what if I need to create another method that uses just the ordensInternas field? Then again, I'd get an error...

So, my doubt here is: if I need to use the ordensAtrasadas field from the entity, will I have to create another class just to implement another mapper? Or is there a way that I can do any conditional in my current OrdemMapper class?

bcr666 :

Just put your assignments in individual try-catch statements.

public class OrdemMapper implements RowMapper<OrdemDeServicoCount> {

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

        OrdemDeServicoCount ordens = new OrdemDeServicoCount();

        try {
            ordens.setOrdensInternas(rs.getLong("ordensInternas"));
        } catch (SQLException ex) {
            // This will happen if the columnIndex is invalid among other things
        }

        try {
            ordens.setOrdensAtrasadas(rs.getLong("ordensAtrasadas"));
        } catch (SQLException ex) {
            // This will happen if the columnIndex is invalid among other things
        }

        return ordens;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=291316&siteId=1