Get only one row from jdbcTemplate query for performance optimization

Viewed 1128
jdbcTemplate.query(getQuery(id),
        rs -> {
            if(rs.next()) {
                mainDTO.setSim(rs.getString("sim"));
                mainDTO.setImei(rs.getString("imei"));
            }
        });

I use above code fragment to retrieve data from database and getting more than 100 records. But for all the records, sim and imei numbers are same. other fields are different. When executing above code I can get sim and imei number from the first record itself. but query run on all over the records and hence it take more than 3 seconds to complete. here is the problem. enter image description here How I can stop retrieving other records after I got the value for sim and imei from the first record. I cant change the sql query as the documentation and need to do the optimization in java code itself.

how can I optimize this to perform within below 100 mills.

1 Answers

You have two choices, either limit using a SQL query or use JdbcTemplate#setMaxRows:

SQL

You need to edit the query including what columns are about to be selected and the table name:

SELECT * FROM table LIMIT 1

JDBC

Use JdbcTemplate#setMaxRows to configure the JdbcTemplate to return up to one row:

jdbcTemplate.setMaxRows(1);

I guess it mimics Statement#setMaxRows.

Related