简体   繁体   中英

How to fetch record from db by ID?

I got this code, but I think this is bad approach, what if there are like 100k results, it will return 100k new People? Are there any other methods that I could use for eg ResultSetExtractor but Im not quite sure how to implement that. Also, should I use try catch block?

   public Optional<Person> getPerson(int id) {
        String sql = "SELECT id, name FROM people WHERE id = ?";
        List<Person> people = jdbcTemplate.query(sql, (result, index) -> {
            return new Person(
                    result.getInt("id"),
                    result.getString("name")
            );
        }, id);

        return people.stream().findFirst();
    }

in a correct design the id field should be unique for every person so this code should only find 1 person as a result. If the id field is not unique then it is not a good design but the code you wrote would be correct. You dont need try - catch because you a are using a list to store the results so even if theres more than 1 result it wont produce an exception. But that also doesnt make sense because in the end the method is only returning 1 person (people.stream.findFirst()).

If you change the query from

"SELECT id, name FROM people WHERE id = ?"

to

"SELECT id, name FROM people WHERE id = ? LIMIT 1"

it will only return the first person with a matching id .

However, id should ideally be unique for each person and the original query will return atmost one result in that case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM