查询
查询是一个承载结果的SQL语句,用以返回数据库的结果集。
List<Map<String, Object>> users =
handle.createQuery("SELECT id, name FROM user ORDER BY id ASC")
.mapToMap()
.list();
assertThat(users).containsExactly(
map("id", 1, "name", "Alice"),
map("id", 2, "name", "Bob"));
- mapToMap
对于单行,您可以使用findOnly()
,它只需要一行(或抛出异常):
String name = handle.select("select name from users where id = ?", 3)
.mapTo(String.class)
.findOnly();
- Handle的select语句,同execute,可带参数
您还可以使用findFirst()
,它返回Optional
映射类型的一个:
Optional<String> name = handle.createUpdate("select name from users where id = :id")
.bind("id", 3)
.mapTo(String.class)
.findFirst();
可以在列表中返回多个结果行:
List<String> name = handle.createQuery(
"select title from films where genre = :genre order by title")
.bind("genre", "Action")
.mapTo(String.class)
.list();
对于其他collections,使用Collectors
:
Set<String> name = handle.createQuery(
"select title from films where genre = :genre order by title")
.bind("genre", "Action")
.mapTo(String.class)
.collect(Collectors.toSet());
您还可以把结果转化成流:
handle.createQuery(
"select title from films where genre = :genre order by title")
.mapTo(String.class)
.useStream(stream -> {
// do stuff with stream
});
到目前为止,所有示例都显示了String
结果类型。当然,您可以映射到许多其他数据类型:
LocalDate releaseDate = handle.createQuery(
"select release_date from films where name = :name")
.bind("name", "Star Wars: A New Hope")
.mapTo(LocalDate.class)
.findOnly();