org.jdbi.v3.core.statement.Update.executeAndReturnGeneratedKeys()方法的使用及代码示例

x33g5p2x  于2022-02-01 转载在 其他  
字(10.3k)|赞(0)|评价(0)|浏览(101)

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

Update.executeAndReturnGeneratedKeys介绍

[英]Execute the statement and returns any auto-generated keys. This requires the JDBC driver to support the Statement#getGeneratedKeys() method.
[中]执行该语句并返回所有自动生成的键。这需要JDBC驱动程序支持语句#getGeneratedKeys()方法。

代码示例

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

public SqlUpdateHandler(Class<?> sqlObjectType, Method method) {
  super(sqlObjectType, method);
  if (method.isAnnotationPresent(UseRowReducer.class)) {
    throw new UnsupportedOperationException("Cannot declare @UseRowReducer on a @SqlUpdate method.");
  }
  boolean isGetGeneratedKeys = method.isAnnotationPresent(GetGeneratedKeys.class);
  QualifiedType<?> returnType = QualifiedType.of(
    GenericTypes.resolveType(method.getGenericReturnType(), sqlObjectType))
    .with(getQualifiers(method));
  if (isGetGeneratedKeys) {
    ResultReturner magic = ResultReturner.forMethod(sqlObjectType, method);
    String[] columnNames = method.getAnnotation(GetGeneratedKeys.class).value();
    this.returner = update -> {
      ResultBearing resultBearing = update.executeAndReturnGeneratedKeys(columnNames);
      UseRowMapper useRowMapper = method.getAnnotation(UseRowMapper.class);
      ResultIterable<?> iterable = useRowMapper == null
          ? resultBearing.mapTo(returnType)
          : resultBearing.map(rowMapperFor(useRowMapper));
      return magic.mappedResult(iterable, update.getContext());
    };
  } else if (isNumeric(method.getReturnType())) {
    this.returner = update -> update.execute();
  } else if (isBoolean(method.getReturnType())) {
    this.returner = update -> update.execute() > 0;
  } else {
    throw new UnableToCreateSqlObjectException(invalidReturnTypeMessage(method, returnType));
  }
}

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

@Test
  public void testDelete() {
    Handle h = dbRule.openHandle();

    Update insert = h.createUpdate("insert into something_else (name) values (:name)");
    insert.bind("name", "Brian");
    Long id1 = insert.executeAndReturnGeneratedKeys().mapTo(long.class).findOnly();

    assertThat(id1).isNotNull();

    Update delete = h.createUpdate("delete from something_else where id = :id");
    delete.bind("id", id1);
    Optional<Long> id2 = delete.executeAndReturnGeneratedKeys().mapTo(long.class).findFirst();

    assertThat(id2.isPresent()).isFalse();
  }
}

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

@Test
public void testUpdate() {
  Handle h = dbRule.openHandle();
  Update insert = h.createUpdate("insert into something_else (name) values (:name)");
  insert.bind("name", "Brian");
  Long id1 = insert.executeAndReturnGeneratedKeys().mapTo(long.class).findOnly();
  assertThat(id1).isNotNull();
  Update update = h.createUpdate("update something_else set name = :name where id = :id");
  update.bind("id", id1);
  update.bind("name", "Tom");
  Optional<Long> id2 = update.executeAndReturnGeneratedKeys().mapTo(long.class).findFirst();
  assertThat(id2.isPresent()).isFalse();
}

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

@Test
public void testInsert() {
  Handle h = dbRule.openHandle();
  Update insert1 = h.createUpdate("insert into something_else (name) values (:name)");
  insert1.bind("name", "Brian");
  Long id1 = insert1.executeAndReturnGeneratedKeys().mapTo(long.class).findOnly();
  assertThat(id1).isNotNull();
  Update insert2 = h.createUpdate("insert into something_else (name) values (:name)");
  insert2.bind("name", "Tom");
  Long id2 = insert2.executeAndReturnGeneratedKeys().mapTo(long.class).findOnly();
  assertThat(id2).isNotNull();
  assertThat(id2).isGreaterThan(id1);
}

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

@Test
// tag::fluent[]
public void fluentInsertKeys() {
  db.useHandle(handle -> {
    User data = handle.createUpdate("INSERT INTO users (name) VALUES(?)")
        .bind(0, "Data")
        .executeAndReturnGeneratedKeys()
        .mapTo(User.class)
        .findOnly();
    assertEquals(1, data.id); // This value is generated by the database
    assertEquals("Data", data.name);
  });
}
// end::fluent[]

代码示例来源:origin: Apicurio/apicurio-studio

/**
 * @see io.apicurio.hub.core.storage.IStorage#addContent(java.lang.String, java.lang.String, io.apicurio.hub.api.beans.ApiContentType, java.lang.String)
 */
@Override
public long addContent(String userId, String designId, ApiContentType type, String data) throws StorageException {
  logger.debug("Inserting a 'command' content row for: {}", designId);
  try {
    return this.jdbi.withHandle( handle -> {
      // Insert a row in the api_content table.  Retrieve the ID.
      String statement = sqlStatements.insertContent();
      CharacterStreamArgument contentClob = new CharacterStreamArgument(new StringReader(data), data.length());
      Long contentVersion = handle.createUpdate(statement)
         .bind(0, Long.parseLong(designId))
         .bind(1, type.getId())
         .bind(2, contentClob)
         .bind(3, userId)
         .bind(4, new Date())
         .executeAndReturnGeneratedKeys("version")
         .mapTo(Long.class)
         .findOnly();
      return contentVersion;
    });
  } catch (Exception e) {
    throw new StorageException("Error adding content entry for API design.", e);
  }
}

代码示例来源:origin: io.apicurio/apicurio-studio-be-hub-core

/**
 * @see io.apicurio.hub.core.storage.IStorage#addContent(java.lang.String, java.lang.String, io.apicurio.hub.api.beans.ApiContentType, java.lang.String)
 */
@Override
public long addContent(String userId, String designId, ApiContentType type, String data) throws StorageException {
  logger.debug("Inserting a 'command' content row for: {}", designId);
  try {
    return this.jdbi.withHandle( handle -> {
      // Insert a row in the api_content table.  Retrieve the ID.
      String statement = sqlStatements.insertContent();
      CharacterStreamArgument contentClob = new CharacterStreamArgument(new StringReader(data), data.length());
      Long contentVersion = handle.createUpdate(statement)
         .bind(0, Long.parseLong(designId))
         .bind(1, type.getId())
         .bind(2, contentClob)
         .bind(3, userId)
         .bind(4, new Date())
         .executeAndReturnGeneratedKeys("version")
         .mapTo(Long.class)
         .findOnly();
      return contentVersion;
    });
  } catch (Exception e) {
    throw new StorageException("Error adding content entry for API design.", e);
  }
}

代码示例来源:origin: org.trellisldp.ext/trellis-db

private static int updateResource(final Handle handle, final Metadata metadata, final Dataset dataset,
    final Instant time, final boolean isDelete) {
  handle.execute("DELETE FROM resource WHERE subject = ?", metadata.getIdentifier().getIRIString());
  final String query
    = "INSERT INTO resource (subject, interaction_model, modified, deleted, is_part_of, acl, "
    + "ldp_member, ldp_membership_resource, ldp_has_member_relation, ldp_is_member_of_relation, "
    + "ldp_inserted_content_relation, binary_location, binary_format) "
    + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
  // Set ldp:insertedContentRelation only for LDP-IC and LDP-DC resources
  final String icr = asList(LDP.DirectContainer, LDP.IndirectContainer).contains(metadata.getInteractionModel())
    ? metadata.getInsertedContentRelation().orElse(LDP.MemberSubject).getIRIString() : null;
  try (final Update update = handle.createUpdate(query)
      .bind(0, metadata.getIdentifier().getIRIString())
      .bind(1, metadata.getInteractionModel().getIRIString())
      .bind(2, time.toEpochMilli())
      .bind(3, isDelete)
      .bind(4, metadata.getContainer().map(IRI::getIRIString).orElse(null))
      .bind(5, dataset.contains(of(PreferAccessControl), null, null, null))
      .bind(6, metadata.getMembershipResource().map(IRI::getIRIString)
        .map(str -> str.split("#")[0]).orElse(null))
      .bind(7, metadata.getMembershipResource().map(IRI::getIRIString).orElse(null))
      .bind(8, metadata.getMemberRelation().map(IRI::getIRIString).orElse(null))
      .bind(9, metadata.getMemberOfRelation().map(IRI::getIRIString).orElse(null))
      .bind(10, icr)
      .bind(11, metadata.getBinary().map(BinaryMetadata::getIdentifier).map(IRI::getIRIString).orElse(null))
      .bind(12, metadata.getBinary().flatMap(BinaryMetadata::getMimeType).orElse(null))) {
    return update.executeAndReturnGeneratedKeys("id").mapTo(Integer.class).findOnly();
  }
}

代码示例来源:origin: Apicurio/apicurio-studio

/**
 * @see io.apicurio.hub.core.storage.IStorage#createCodegenProject(java.lang.String, io.apicurio.hub.core.beans.CodegenProject)
 */
@Override
public String createCodegenProject(String userId, CodegenProject project) throws StorageException {
  logger.debug("Inserting a codegen project: {}", project.getType());
  try {
    return this.jdbi.withHandle( handle -> {
      String statement = sqlStatements.insertCodegenProject();
      String attrs = CodegenProjectRowMapper.toString(project.getAttributes());
      CharacterStreamArgument attributesClob = new CharacterStreamArgument(new StringReader(attrs), attrs.length());
      String projectId = handle.createUpdate(statement)
         .bind(0, project.getCreatedBy())
         .bind(1, project.getCreatedOn())
         .bind(2, project.getCreatedBy())
         .bind(3, project.getCreatedOn())
         .bind(4, Long.valueOf(project.getDesignId()))
         .bind(5, project.getType().toString())
         .bind(6, attributesClob)
         .executeAndReturnGeneratedKeys("id")
         .mapTo(String.class)
         .findOnly();
      return projectId;
    });
  } catch (Exception e) {
    throw new StorageException("Error inserting codegen project.", e);
  }
}

代码示例来源:origin: io.apicurio/apicurio-studio-be-hub-core

/**
 * @see io.apicurio.hub.core.storage.IStorage#createCodegenProject(java.lang.String, io.apicurio.hub.core.beans.CodegenProject)
 */
@Override
public String createCodegenProject(String userId, CodegenProject project) throws StorageException {
  logger.debug("Inserting a codegen project: {}", project.getType());
  try {
    return this.jdbi.withHandle( handle -> {
      String statement = sqlStatements.insertCodegenProject();
      String attrs = CodegenProjectRowMapper.toString(project.getAttributes());
      CharacterStreamArgument attributesClob = new CharacterStreamArgument(new StringReader(attrs), attrs.length());
      String projectId = handle.createUpdate(statement)
         .bind(0, project.getCreatedBy())
         .bind(1, project.getCreatedOn())
         .bind(2, project.getCreatedBy())
         .bind(3, project.getCreatedOn())
         .bind(4, Long.valueOf(project.getDesignId()))
         .bind(5, project.getType().toString())
         .bind(6, attributesClob)
         .executeAndReturnGeneratedKeys("id")
         .mapTo(String.class)
         .findOnly();
      return projectId;
    });
  } catch (Exception e) {
    throw new StorageException("Error inserting codegen project.", e);
  }
}

代码示例来源:origin: io.apicurio/apicurio-studio-be-hub-core

.bind(3, design.getCreatedOn())
.bind(4, asCsv(design.getTags()))
.executeAndReturnGeneratedKeys("id")
.mapTo(String.class)
.findOnly();

代码示例来源:origin: Apicurio/apicurio-studio

.bind(4, asCsv(design.getTags()))
.bind(5, design.getType().name())
.executeAndReturnGeneratedKeys("id")
.mapTo(String.class)
.findOnly();

相关文章