Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

前端 未结 17 1128
执笔经年
执笔经年 2020-11-29 16:22

I am using Jdbctemplate to retrieve a single String value from the db. Here is my method.

    public String test() {
        String cert=null;
        Strin         


        
17条回答
  •  有刺的猬
    2020-11-29 16:56

    Using Java 8 or above you can use an Optional and Java Streams.

    So you can simply use the JdbcTemplate.queryForList() method, create a Stream and use Stream.findFirst() which will return the first value of the Stream or an empty Optional:

    public Optional test() {
        String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
        return jdbc.queryForList(sql, String.class)
                .stream().findFirst();
    }
    

    To improve the performance of the query you can append LIMIT 1 to your query, so not more than 1 item is transferred from the database.

提交回复
热议问题