jdbi

  JDBI是一个使用方便的SQL开发库,用符合Java语言习惯的集合、Bean等方式,提供关系数据库访问接口,同时保留了JDBC类似的信息。JDBI提供了链式和SQL两种风格的API。

  jdbi的网址是: http://jdbi.org/jdbi2/

  maven依赖,可以在https://mvnrepository.com/ 中查到

<dependency>
  <groupId>org.jdbi</groupId>
  <artifactId>jdbi</artifactId>
  <version>${jdbi.version}</version>
</dependency>

  

  官网上链式风格的例子:

// using in-memory H2 database
DataSource ds = JdbcConnectionPool.create("jdbc:h2:mem:test",
                                          "username",
                                          "password");
DBI dbi = new DBI(ds);
Handle h = dbi.open();
h.execute("create table something (id int primary key, name varchar(100))");

h.execute("insert into something (id, name) values (?, ?)", 1, "Brian");

String name = h.createQuery("select name from something where id = :id")
                    .bind("id", 1)
                    .map(StringColumnMapper.INSTANCE)
                    .first();
                    
assertThat(name, equalTo("Brian"));

h.close();

    

  SQL风格的例子:

public interface MyDAO
{
  @SqlUpdate("create table something (id int primary key, name varchar(100))")
  void createSomethingTable();

  @SqlUpdate("insert into something (id, name) values (:id, :name)")
  void insert(@Bind("id") int id, @Bind("name") String name);

  @SqlQuery("select name from something where id = :id")
  String findNameById(@Bind("id") int id);

  /**
   * close with no args is used to close the connection
   */
  void close();
}

  更为复杂的应用,Bean映射:

public class Something
{
  private int id;
  private String name;
  private ValueType value;
  
  public Something() { }

  public Something(int id, String name, ValueType value)
  {
    this.id = id;
    this.name = name;
    this.value = value;
  }

  public int getId()
  {
    return id;
  }

  public void setId(int id)
  {
    this.id = id;
  }

  public String getName()
  {
    return name;
  }

  public void setName(String name)
  {
    this.name = name;
  }
  
  public ValueType getValue()
  {
    return value;
  }
  
  public void setValue(ValueType value)
  {
    this.value = value;
  }
}

public class SomethingMapper implements ResultSetMapper<Something>
{
  public Something map(int index, ResultSet r, StatementContext ctx) throws SQLException
  {
    return new Something(r.getInt("id"), r.getString("name"), ValueType.valueOf(r.getString("value"));
  }
}
@RegisterMapper(SomethingMapper.class)
public interface AnotherQuery
{
  @SqlQuery("select id, name, value from something where id = :id")
  Something findById(@Bind("id") int id);
}

  dropwizard中默认提供了对jdbi的支持,可以参考https://www.dropwizard.io/0.7.1/docs/manual/jdbi.html

原文地址:https://www.cnblogs.com/lnlvinso/p/9971947.html