在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Java 简单操作接口:JDBI

2017-2-7 13:43| 发布者: zhangjf| 查看: 577| 评论: 0

摘要: jDBI 提供一个 Java 简单操作接口, 它不是一个抽象层而是一个类库是的公共的操作更简单、还有能力去做一些更复杂的操作。 JDBI 是 Java 的 SQL 便捷操作库,尝试使用集合,beans 等等来暴露 Java 中的关系型数据库 ...

jDBI 提供一个 Java 简单操作接口, 它不是一个抽象层而是一个类库是的公共的操作更简单、还有能力去做一些更复杂的操作。

JDBI 是 Java 的 SQL 便捷操作库,尝试使用集合,beans 等等来暴露 Java 中的关系型数据库,可以维护相同级别的 JDBC。提供两个不同样式的 APIs:fluent 和 sql object。

Fluent API

  1. // using in-memory H2 database
  2. DataSource ds = JdbcConnectionPool.create("jdbc:h2:mem:test",
  3. "username",
  4. "password");
  5. DBI dbi = new DBI(ds);
  6. Handle h = dbi.open();
  7. h.execute("create table something (id int primary key, name varchar(100))");
  8. h.execute("insert into something (id, name) values (?, ?)", 1, "Brian");
  9. String name = h.createQuery("select name from something where id = :id")
  10. .bind("id", 1)
  11. .map(StringMapper.FIRST)
  12. .first();
  13. assertThat(name, equalTo("Brian"));
  14. h.close();
复制代码

SQL Object API

  1. public interface MyDAO
  2. {
  3. @SqlUpdate("create table something (id int primary key, name varchar(100))")
  4. void createSomethingTable();
  5. @SqlUpdate("insert into something (id, name) values (:id, :name)")
  6. void insert(@Bind("id") int id, @Bind("name") String name);
  7. @SqlQuery("select name from something where id = :id")
  8. String findNameById(@Bind("id") int id);
  9. /**
  10. * close with no args is used to close the connection
  11. */
  12. void close();
  13. }
复制代码

Maven:

  1. <dependency>
  2. <groupId>org.jdbi</groupId>
  3. <artifactId>jdbi</artifactId>
  4. <version>${jdbi.version}</version>
  5. </dependency>
复制代码

项目主页:http://www.open-open.com/lib/view/home/1442891121388

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-9 15:14

Copyright 2015-2025 djqfx

返回顶部