【Java】jdbctemplate笔记(DataClassRowMapper)【Java】jdbctemplate备忘录(DataClassRowMapper)

在处理数据库数据时,关于JdbcTemplate中的数据类型。

我现在正在学习SpringBoot,参考书(《成为专业Spring开发者的入门指南》)中发现了jdbctemplate的使用方法中的一些有用功能,为了不忘记,我将在下面进行简略写下来。

在SpringBoot的jdbctemplate中,以前我们使用queryForMap方法在DAO文件中进行转换来从数据库中提取一条记录。

以下的代码是用于根据ID在预约管理系统中搜索使用的预约信息的代码。它接受与预约关联的ID作为参数,并实例化Reserve类型,并使用map按类型进行转换。

    public Reserve idFind(String id) {
        String sql = "SELECT * FROM reserve WHERE id = ?";
        try {
            Map<String, Object> map = jdbcTemplate.queryForMap(sql, id);
            Reserve reserve = new Reserve(
                    map.get("id").toString(),
                    ((Date) (map.get("date"))).toLocalDate(),
                    ((Time) map.get("time")).toLocalTime(),
                    map.get("menu").toString(),
                    map.get("name").toString(),
                    map.get("email").toString(),
                    map.get("tel").toString());
            return reserve;
        } catch (IncorrectResultSizeDataAccessException e) {
            return null;
        }
    }

使用这段代码确实可以提取数据,但我一直觉得自从写下可读性很差的原因时,这种感觉一直存在。
通过使用DataClassRowMapper,在从数据库提取数据时会自动进行转换,所以不必写额外的转换代码。
官方参考资料(DataClassRowMapper)

使用这个代码,并对其进行了修改,修改后的代码如下。

    public Reserve idFind(String id) {
        String sql = "SELECT * FROM reserve WHERE id = ?";
        try {
            Reserve reserve = jdbcTemplate.queryForObject(sql,new DataClassRowMapper<>(Reserve.class),id);
            return reserve;
        } catch (IncorrectResultSizeDataAccessException e) {
            return null;
        }
    }

诚实真的非常方便..
真希望早点知道(笑)

因为我仍然是个初学者,所以我只能通过参考书等获取这些方便的功能。但我很想知道有经验的工程师们是如何学习的。请务必在评论区告诉我。?‍♂️