org.skife.jdbi.v2.Query类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(10.8k)|赞(0)|评价(0)|浏览(192)

本文整理了Java中org.skife.jdbi.v2.Query类的一些代码示例,展示了Query类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Query类的具体详情如下:
包路径:org.skife.jdbi.v2.Query
类名称:Query

Query介绍

[英]Statement providing convenience result handling for SQL queries.
[中]语句,为SQL查询提供方便的结果处理。

代码示例

代码示例来源:origin: apache/incubator-druid

.createQuery(
    StringUtils.format("SELECT COUNT(*) FROM %1$s WHERE %2$s = :key", tableName, keyColumn)
  .bind("key", key)
  .map(IntegerMapper.FIRST)
  .first();
if (count == 0) {
 handle.createStatement(
   StringUtils.format(
     "INSERT INTO %1$s (%2$s, %3$s) VALUES (:key, :value)",
    .bind("key", key)
    .bind("value", value)
    .execute();
} else {
 handle.createStatement(
   StringUtils.format(
     "UPDATE %1$s SET %3$s=:value WHERE %2$s=:key",

代码示例来源:origin: apache/incubator-druid

@Override
 public List<String> inTransaction(Handle handle, TransactionStatus status)
 {
  return handle.createQuery(reverseFetchQuery)
         .bind("val", value)
         .map(StringMapper.FIRST)
         .list();
 }
});

代码示例来源:origin: apache/incubator-druid

private List<SegmentIdWithShardSpec> getPendingSegmentsForIntervalWithHandle(
  final Handle handle,
  final String dataSource,
  final Interval interval
) throws IOException
{
 final List<SegmentIdWithShardSpec> identifiers = new ArrayList<>();
 final ResultIterator<byte[]> dbSegments =
   handle.createQuery(
     StringUtils.format(
       "SELECT payload FROM %1$s WHERE dataSource = :dataSource AND start <= :end and %2$send%2$s >= :start",
       dbTables.getPendingSegmentsTable(), connector.getQuoteString()
     )
   )
      .bind("dataSource", dataSource)
      .bind("start", interval.getStart().toString())
      .bind("end", interval.getEnd().toString())
      .map(ByteArrayMapper.FIRST)
      .iterator();
 while (dbSegments.hasNext()) {
  final byte[] payload = dbSegments.next();
  final SegmentIdWithShardSpec identifier = jsonMapper.readValue(payload, SegmentIdWithShardSpec.class);
  if (interval.overlaps(identifier.getInterval())) {
   identifiers.add(identifier);
  }
 }
 dbSegments.close();
 return identifiers;
}

代码示例来源:origin: apache/incubator-druid

@Override
public boolean tableExists(Handle handle, String tableName)
{
 return !handle.createQuery("select * from SYS.SYSTABLES where tablename = :tableName")
        .bind("tableName", StringUtils.toUpperCase(tableName))
        .list()
        .isEmpty();
}

代码示例来源:origin: apache/incubator-druid

@Override
 public Timestamp withHandle(Handle handle)
 {
  final String query = StringUtils.format(
    "SELECT MAX(%s) FROM %s",
    tsColumn, table
  );
  return handle
    .createQuery(query)
    .map(TimestampMapper.FIRST)
    .first();
 }
}

代码示例来源:origin: org.jdbi/jdbi

@Test
public void testDoubleCleanup()
  throws Exception
{
  final Handle handle = dbi.open();
  final Query<Integer> q = handle
    .createQuery("SELECT id FROM something")
    .cleanupHandle()
    .cleanupHandle()
    .mapTo(Integer.class);
  final ResultIterator<Integer> it = q.iterator();
  while (it.hasNext()) {
    it.next();
  }
  assertFalse(it.hasNext());
  assertTrue(handle.getConnection().isClosed());
}

代码示例来源:origin: org.jdbi/jdbi

@Test
public void testDefines() throws Exception
{
  handle.attach(Kangaroo.class).weirdInsert("something", "id", "name", 5, "Bouncer");
  String name = handle.createQuery("select name from something where id = 5")
            .mapTo(String.class)
            .first();
  assertThat(name, equalTo("Bouncer"));
}

代码示例来源:origin: org.jdbi/jdbi

@Test
public void testDoesNotExist() throws Exception
{
  h.execute("insert into something (id, name) values (1, 'Coda')");
  h.registerContainerFactory(new MaybeContainerFactory());
  Maybe<String> rs = h.createQuery("select name from something where id = :id")
            .bind("id", 2)
            .mapTo(String.class)
            .first(Maybe.class);
  assertThat(rs.isKnown(), equalTo(false));
}

代码示例来源:origin: rakam-io/rakam

private Lock tryLock(String name, int tryCount) {
  try {
    if (currentHandle.getConnection().isClosed()) {
      synchronized (this) {
        currentHandle = dbi.open();
    Boolean first = currentHandle.createQuery("select pg_try_advisory_lock(:name)")
        .bind("name", name.hashCode())
        .map(BooleanMapper.FIRST)
        .first();
      currentHandle.createQuery("select pg_advisory_unlock(:name)")
          .bind("name", name.hashCode())
          .map(BooleanMapper.FIRST)
          .first();
    };
  } catch (SQLException e) {
    try {
      if (currentHandle.getConnection().isClosed()) {
        synchronized (this) {
          currentHandle = dbi.open();
        currentHandle = dbi.open();

代码示例来源:origin: org.jdbi/jdbi

@Test
public void testFluentApi() throws Exception
{
  Map<String, Team> teams = handle.createQuery("select t.name as teamName, " +
                         "       t.mascot as mascot, " +
                         "       p.name as personName, " +
                         "       p.role as role " +
                         "from team t inner join person p on (t.name = p.team)")
                  .map(TeamPersonJoinRow.class)
                  .fold(Maps.<String, Team>newHashMap(), new TeamFolder());
  assertThat(teams, equalTo(expected));
}

代码示例来源:origin: org.jdbi/jdbi

@Test
public void testRegisterOnDBI() throws Exception
{
  dbi.registerArgumentFactory(new NameAF());
  Handle h2 = dbi.open();
  h2.createStatement("insert into something (id, name) values (:id, :name)")
   .bind("id", 7)
   .bind("name", new Name("Brian", "McCallister"))
   .execute();
  String full_name = h.createQuery("select name from something where id = 7").mapTo(String.class).first();
  assertThat(full_name, equalTo("Brian McCallister"));
  h2.close();
}

代码示例来源:origin: org.kill-bill.commons/killbill-jdbi

@Test
@Category(JDBIQuarantineTests.class) // Feature disabled
public void testRegisterOnHandle() throws Exception
{
  h.registerArgumentFactory(new NameAF());
  h.createStatement("insert into something (id, name) values (:id, :name)")
   .bind("id", 7)
   .bind("name", new Name("Brian", "McCallister"))
   .execute();
  String full_name = h.createQuery("select name from something where id = 7").map(StringMapper.FIRST).first();
  assertThat(full_name, equalTo("Brian McCallister"));
}

代码示例来源:origin: org.jdbi/jdbi

@Test
public void testRegisterOnHandle() throws Exception
{
  h.registerArgumentFactory(new NameAF());
  h.createStatement("insert into something (id, name) values (:id, :name)")
   .bind("id", 7)
   .bind("name", new Name("Brian", "McCallister"))
   .execute();
  String full_name = h.createQuery("select name from something where id = 7").mapTo(String.class).first();
  assertThat(full_name, equalTo("Brian McCallister"));
}

代码示例来源:origin: org.jdbi/jdbi

@Test
public void testOnList() throws Exception
{
  h.registerContainerFactory(new ImmutableListContainerFactory());
  h.execute("insert into something (id, name) values (1, 'Coda')");
  h.execute("insert into something (id, name) values (2, 'Brian')");
  ImmutableList<String> rs = h.createQuery("select name from something order by id")
                .mapTo(String.class)
                .list(ImmutableList.class);
  assertThat(rs, equalTo(ImmutableList.of("Coda", "Brian")));
}

代码示例来源:origin: org.jdbi/jdbi

@Test
public void testBindConstantValue() throws Exception
{
  UsesBatching b = handle.attach(UsesBatching.class);
  List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5);
  b.withConstantValue(ids, "Johan");
  assertThat(b.size(), equalTo(5));
  List<String> names = handle.createQuery("select distinct name from something")
                .mapTo(String.class)
                .list();
  assertThat(names, equalTo(Arrays.asList("Johan")));
}

代码示例来源:origin: rakam-io/rakam

public List<ProjectKeyPermission> apiKeyOwners(int project, List<String> readKeys) {
  try (Handle handle = dbi.open()) {
    return handle.createQuery("select read_key, web_user.email, web_user_api_key.created_at from web_user_api_key \n" +
        "join web_user_api_key_permission permission on (permission.api_key_id = web_user_api_key.id and permission.read_permission)\n" +
        "join web_user on (web_user.id = permission.user_id)\n" +
        "where read_key = any (:keys) and web_user_api_key.project_id = :project")
        .bind("keys", handle.getConnection().createArrayOf("text", readKeys.toArray()))
        .bind("project", project)
        .map((index, r, ctx) -> {
          return new ProjectKeyPermission(r.getString(1), r.getString(2), r.getTimestamp(3).toInstant());
        }).list();
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: rakam-io/rakam

@ApiParam("type_id") int type_id,
  @ApiParam("emails") List<String> emails) {
try (Handle handle = dbi.open()) {
  int id = handle.createQuery("INSERT INTO scheduled_email (project_id, user_id, date_interval, hour_of_day, name, type, type_id, emails, enabled) " +
      "VALUES (:project, :user_id, :date_interval, :hour_of_day, :name, :type, :type_id, :emails, true) RETURNING id")
      .bind("project", project.project)
      .bind("user_id", project.userId)
      .bind("date_interval", date_interval)
      .bind("hour_of_day", hour_of_day)
      .bind("name", name)
      .bind("type", type)
      .bind("type_id", type_id)
      .bind("emails", handle.getConnection().createArrayOf("text", emails.toArray()))
      .map(IntegerMapper.FIRST).first();

代码示例来源:origin: org.jdbi/jdbi

@Test
public void testJustNext() throws Exception {
  h.createStatement("insert into something (id, name) values (1, 'eric')").execute();
  h.createStatement("insert into something (id, name) values (2, 'brian')").execute();
  h.createStatement("insert into something (id, name) values (3, 'john')").execute();
  ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id")
    .cleanupHandle()
    .iterator();
  it.next();
  it.next();
  it.next();
}

代码示例来源:origin: apache/incubator-druid

@Override
public Map<Long, LockType> withHandle(Handle handle)
 return handle.createQuery(
   StringUtils.format(
     "SELECT id, lock_payload FROM %1$s WHERE %2$s_id = :entryId",
        .bind("entryId", entryId)
        .map(
          new ResultSetMapper<Pair<Long, LockType>>()
        .fold(
          Maps.newLinkedHashMap(),
          new Folder3<Map<Long, LockType>, Pair<Long, LockType>>()

代码示例来源:origin: rakam-io/rakam

public void revokeApiKeys(int user, int project, String masterKey) {
  try (Handle handle = dbi.open()) {
    if (!hasMasterAccess(handle, project, user)) {
      throw new RakamException("You do not have master key permission", UNAUTHORIZED);
    }
    try {
      handle.createStatement("DELETE FROM web_user_api_key " +
          "WHERE user_id = :user_id AND project_id = :project AND master_key = :masterKey")
          .bind("user_id", user)
          .bind("project", project)
          .bind("masterKey", masterKey).execute();
    } catch (Throwable e) {
      if (e.getMessage().contains("web_user_api_key_permission")) {
        List<String> list = handle.createQuery("SELECT web_user.email FROM web_user_api_key_permission permission " +
            "JOIN web_user ON (web_user.id = permission.user_id) " +
            "WHERE api_key_id in (SELECT id FROM web_user_api_key WHERE master_key = :masterKey and user_id = :userId and project_id = :project)")
            .bind("masterKey", masterKey).bind("userId", user).bind("project", project).map(StringMapper.FIRST).list();
        if (!list.isEmpty()) {
          throw new RakamException("Users [" + list.stream().collect(Collectors.joining(", ")) + "] use this key." +
              " You need to revoke the access of the user in order to be able to delete this key", BAD_REQUEST);
        }
      }
      throw e;
    }
  }
}

相关文章