Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
public class OrderRepository {
private static final RowMapper<Order> rowMapper = (rs, i) -> new Order(rs.getLong("id"));
private final JdbcTemplate jdbcTemplate;
public OrderRepository(final JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
public Optional<Order> findOrderById(Long id) {
List<Order> query = jdbcTemplate.query("select * from orders where id=:id", rowMapper, id);
if (query.size() > 1) throw new RuntimeException("Too many results from findOrderById.");
return query.size() == 1 ? Optional.of(query.get(0)) : Optional.empty();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment