Last active
May 18, 2018 12:59
-
-
Save soudmaijer/f1adc4ed4c048c8edd68bf237a5a7320 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
@Repository | |
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