当前位置: 首页>>代码示例>>Java>>正文


Java Insert类代码示例

本文整理汇总了Java中com.datastax.driver.core.querybuilder.Insert的典型用法代码示例。如果您正苦于以下问题:Java Insert类的具体用法?Java Insert怎么用?Java Insert使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Insert类属于com.datastax.driver.core.querybuilder包,在下文中一共展示了Insert类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: insertAndSelect

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
/**
 * Cassandra {@link com.datastax.driver.core.Statement}s can be used together with {@link CassandraTemplate} and the
 * mapping layer.
 */
@Test
public void insertAndSelect() {

	Insert insert = QueryBuilder.insertInto("users").value("user_id", 42L) //
			.value("uname", "heisenberg") //
			.value("fname", "Walter") //
			.value("lname", "White") //
			.ifNotExists(); //

	template.execute(insert);

	User user = template.selectOneById(User.class, 42L);
	assertThat(user.getUsername(), is(equalTo("heisenberg")));

	List<User> users = template.select(QueryBuilder.select().from("users"), User.class);
	assertThat(users, hasSize(1));
	assertThat(users.get(0), is(equalTo(user)));
}
 
开发者ID:Just-Fun,项目名称:spring-data-examples,代码行数:23,代码来源:CassandraOperationsIntegrationTests.java

示例2: save

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
private Optional<Event> save(EventEntity entity, boolean ifNotExists) {
    if (entity.getId() == null) {
        entity.setId(UUIDs.timeBased());
    }
    Insert insert = QueryBuilder.insertInto(getColumnFamilyName())
            .value(ModelConstants.ID_PROPERTY, entity.getId())
            .value(ModelConstants.EVENT_TENANT_ID_PROPERTY, entity.getTenantId())
            .value(ModelConstants.EVENT_ENTITY_TYPE_PROPERTY, entity.getEntityType())
            .value(ModelConstants.EVENT_ENTITY_ID_PROPERTY, entity.getEntityId())
            .value(ModelConstants.EVENT_TYPE_PROPERTY, entity.getEventType())
            .value(ModelConstants.EVENT_UID_PROPERTY, entity.getEventUid())
            .value(ModelConstants.EVENT_BODY_PROPERTY, entity.getBody());
    if (ifNotExists) {
        insert = insert.ifNotExists();
    }
    ResultSet rs = executeWrite(insert);
    if (rs.wasApplied()) {
        return Optional.of(DaoUtil.getData(entity));
    } else {
        return Optional.empty();
    }
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:23,代码来源:CassandraBaseEventDao.java

示例3: Indexer

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
Indexer(Session session, @Nullable Integer indexTtl,
    @Nullable ConcurrentMap<PartitionKeyToTraceId, Pair<Long>> sharedState, IndexSupport index) {
  this.index = index;
  this.boundName = UPPER_CAMEL.to(LOWER_HYPHEN, index.getClass().getSimpleName());
  Insert insert = index.declarePartitionKey(QueryBuilder.insertInto(index.table())
      .value("ts", QueryBuilder.bindMarker("ts"))
      .value("trace_id", QueryBuilder.bindMarker("trace_id")));
  if (indexTtl != null) {
    insert.using(QueryBuilder.ttl(QueryBuilder.bindMarker("ttl_")));
  }
  this.prepared = session.prepare(insert);
  this.indexTtl = indexTtl;
  this.session = session;
  this.timestampCodec = new TimestampCodec(session);
  this.sharedState = sharedState;
}
 
开发者ID:liaominghua,项目名称:zipkin,代码行数:17,代码来源:Indexer.java

示例4: managed

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
@Test
public void managed() throws Throwable {
  final CassandraRule rule = CassandraRule.newBuilder()
      .withManagedKeyspace()
      .withManagedTable(TABLE_SCHEMA)
      .build();
  rule.before();

  final Session session = rule.getSession();

  Insert insert = QueryBuilder.insertInto("mytable")
      .value("key", KEY)
      .value("value", VALUE);
  session.execute(insert);

  Statement select = QueryBuilder.select()
      .from("mytable")
      .where(QueryBuilder.eq("key", KEY))
      .limit(1);
  Row result = session.execute(select).all().get(0);

  assertEquals(KEY, result.getString("key"));
  assertEquals(VALUE, result.getBytes("value"));

  rule.after();
}
 
开发者ID:spotify,项目名称:cassandra-extra,代码行数:27,代码来源:CassandraRuleTest.java

示例5: cqlBuilders

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
private static void cqlBuilders() {
    FieldModel model = SampleModels.wrapper();
    Create create = SchemaBuilder.createTable("Field").addClusteringColumn(LOGIN.name(), text())
            .addPartitionKey("snapshot_id", timeuuid());

    model.getFieldInfos().stream().filter(f -> f.id() != LOGIN)
            .forEach(f -> create.addColumn(f.id().name(), cqlType(f)));

    Create.Options createWithOptions = create.withOptions().clusteringOrder(LOGIN.name(), DESC);
    System.out.println(createWithOptions);

    Insert insert = QueryBuilder.insertInto("Field");
    model.stream().forEach(e -> insert.value(e.getKey().name(), e.getValue()));

    System.out.println(insert.getQueryString(codecRegistry()));
}
 
开发者ID:lesfurets,项目名称:dOOv,代码行数:17,代码来源:LiveCode.java

示例6: getAppliedMigrations_shouldQueryAndSortByName

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
@Test
public void getAppliedMigrations_shouldQueryAndSortByName() throws Exception {
    ResultSet appliedMigrationResultSet = mock(ResultSet.class);
    Row row = mock(Row.class);

    when(session.execute(argThat(new CustomMatcher<Insert>("Get applied migrations") {
        @Override
        public boolean matches(Object item) {
            return "SELECT name,status FROM test.migrations;".equals(item.toString());
        }
    }))).thenReturn(appliedMigrationResultSet);
    when(appliedMigrationResultSet.all()).thenReturn(Collections.singletonList(row));
    when(row.getString(0)).thenReturn("001_initial_migration.cql");
    when(row.getString(1)).thenReturn("APPLIED");

    assertThat(client.getAppliedMigrations()).containsOnly("001_initial_migration.cql");
}
 
开发者ID:revinate,项目名称:henicea,代码行数:18,代码来源:MigrationClientTest.java

示例7: getAppliedMigrations_shouldIgnoreFailedAndIncompleteMigrations

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
@Test
public void getAppliedMigrations_shouldIgnoreFailedAndIncompleteMigrations() throws Exception {
    ResultSet appliedMigrationResultSet = mock(ResultSet.class);
    Row row1 = mock(Row.class);
    Row row2 = mock(Row.class);

    when(session.execute(argThat(new CustomMatcher<Insert>("Get applied migrations") {
        @Override
        public boolean matches(Object item) {
            return "SELECT name,status FROM test.migrations;".equals(item.toString());
        }
    }))).thenReturn(appliedMigrationResultSet);
    when(appliedMigrationResultSet.all()).thenReturn(Arrays.asList(row1, row2));

    when(row1.getString(0)).thenReturn("001_initial_migration.cql");
    when(row1.getString(1)).thenReturn("APPLIED");
    when(row2.getString(0)).thenReturn("002_add_stuff.cql");
    when(row2.getString(1)).thenReturn("FAILED");

    assertThat(client.getAppliedMigrations()).containsOnly("001_initial_migration.cql");
}
 
开发者ID:revinate,项目名称:henicea,代码行数:22,代码来源:MigrationClientTest.java

示例8: runBatchInsert

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
private void runBatchInsert(List<Insert> insertRequest) {
    try {
        Batch batch;
        if (config.getLoggedBatch()) {
            batch = QueryBuilder.batch(insertRequest
                    .toArray(new RegularStatement[insertRequest.size()]));
        } else {
            batch = QueryBuilder.unloggedBatch(insertRequest
                    .toArray(new RegularStatement[insertRequest.size()]));
        }
        totalCassandraInsertRequest.addAndGet(insertRequest.size());
        ResultSetFuture future = cassandraSession.executeAsync(batch);
        CallBackListener listener = new CallBackListener(future, null);
        future.addListener(listener, pool);
        incrementBatchInsertCounter();
        pendingRequestCounter.incrementAndGet();
    } catch (Throwable ex) {
        LOGGER.error("Error publising metrics in MetricCassandraCollector:" + ex.getMessage());
        cassandraErrorCount.increment();
        registerError(ex);
    } finally {
        insertRequest.clear();
    }
}
 
开发者ID:pulsarIO,项目名称:realtime-analytics,代码行数:25,代码来源:MetricCassandraCollector.java

示例9: createPreparedStatements

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
private void createPreparedStatements() {

        Select.Where select = select()
                .all()
                .from( CassandraModel.CF_METRICS_METADATA_NAME )
                .where( eq( KEY, bindMarker() ));

        getValue = DatastaxIO.getSession().prepare( select );

        Insert insert = insertInto( CassandraModel.CF_METRICS_METADATA_NAME )
                .value( KEY, bindMarker() )
                .value( COLUMN1, bindMarker() )
                .value( VALUE, bindMarker() );

        putValue = DatastaxIO.getSession().prepare( insert );
        putValue.setConsistencyLevel( ConsistencyLevel.LOCAL_ONE );
    }
 
开发者ID:rackerlabs,项目名称:blueflood,代码行数:18,代码来源:DMetadataIO.java

示例10: createPreparedStatements

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
/**
 * Create all prepared statements use in this class for metrics_locator
 */
private void createPreparedStatements()  {

    // create a generic select statement for retrieving from metrics_locator
    Select.Where select = QueryBuilder
            .select()
            .all()
            .from( CassandraModel.CF_METRICS_LOCATOR_NAME )
            .where( eq ( KEY, bindMarker() ));
    getValue = DatastaxIO.getSession().prepare( select );

    // create a generic insert statement for inserting into metrics_locator
    Insert insert = QueryBuilder.insertInto( CassandraModel.CF_METRICS_LOCATOR_NAME)
            .using(ttl(TenantTtlProvider.LOCATOR_TTL))
            .value(KEY, bindMarker())
            .value(COLUMN1, bindMarker())
            .value(VALUE, bindMarker());
    putValue = DatastaxIO.getSession()
            .prepare(insert)
            .setConsistencyLevel( ConsistencyLevel.LOCAL_ONE );
}
 
开发者ID:rackerlabs,项目名称:blueflood,代码行数:24,代码来源:DLocatorIO.java

示例11: DDelayedLocatorIO

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
public DDelayedLocatorIO() {

        // create a generic select statement for retrieving from metrics_delayed_locator
        Select.Where select = QueryBuilder
                .select()
                .all()
                .from( CassandraModel.CF_METRICS_DELAYED_LOCATOR_NAME )
                .where( eq ( KEY, bindMarker() ));
        getValue = DatastaxIO.getSession().prepare( select );

        // create a generic insert statement for inserting into metrics_delayed_locator
        Insert insert = QueryBuilder.insertInto( CassandraModel.CF_METRICS_DELAYED_LOCATOR_NAME)
                .using(ttl(TenantTtlProvider.DELAYED_LOCATOR_TTL))
                .value(KEY, bindMarker())
                .value(COLUMN1, bindMarker())
                .value(VALUE, bindMarker());
        putValue = DatastaxIO.getSession()
                .prepare(insert)
                .setConsistencyLevel( ConsistencyLevel.LOCAL_ONE );
    }
 
开发者ID:rackerlabs,项目名称:blueflood,代码行数:21,代码来源:DDelayedLocatorIO.java

示例12: createInsertQuery

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
private Insert createInsertQuery(EntityEvent entityEvent) {
    Insert insert = QueryBuilder.insertInto(tableName);
    insert.value(ENTITY_ID, entityEvent.getEventKey().getEntityId());
    insert.value(VERSION, entityEvent.getEventKey().getVersion());
    insert.value(OP_ID, entityEvent.getOpId());
    insert.value(OP_DATE, entityEvent.getOpDate());
    insert.value(EVENT_TYPE, entityEvent.getEventType());
    insert.value(STATUS, entityEvent.getStatus().name());
    insert.value(AUDIT_INFO, entityEvent.getAuditInfo());
    insert.value(EVENT_DATA, entityEvent.getEventData());
    insert.ifNotExists();
    return insert;
}
 
开发者ID:kloiasoft,项目名称:eventapis,代码行数:14,代码来源:CassandraEventRecorder.java

示例13: storeRefreshToken

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
@Override
public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
  List<RegularStatement> statementList = new ArrayList<RegularStatement>();

  byte[] serializedRefreshToken = SerializationUtils.serialize(refreshToken);
  ByteBuffer bufferedRefreshToken = ByteBuffer.wrap(serializedRefreshToken);

  byte[] serializedAuthentication = SerializationUtils.serialize(authentication);
  ByteBuffer bufferedAuthentication = ByteBuffer.wrap(serializedAuthentication);

  WriteOptions refreshWriteOptions = new WriteOptions();
  if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
    ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
    Date expiration = expiringRefreshToken.getExpiration();
    if (expiration != null) {
      int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L).intValue();
      refreshWriteOptions.setTtl(seconds);
    }
  }

  // Insert into RefreshToken table
  Insert accessInsert = CassandraTemplate.createInsertQuery(RefreshToken.TABLE, new RefreshToken(refreshToken.getValue(), bufferedRefreshToken), refreshWriteOptions, cassandraTemplate.getConverter());
  statementList.add(accessInsert);

  // Insert into RefreshTokenAuthentication table
  Insert authInsert = CassandraTemplate.createInsertQuery(RefreshTokenAuthentication.TABLE, new RefreshTokenAuthentication(refreshToken.getValue(), bufferedAuthentication), refreshWriteOptions, cassandraTemplate.getConverter());
  statementList.add(authInsert);

  Batch batch = QueryBuilder.batch(statementList.toArray(new RegularStatement[statementList.size()]));
  cassandraTemplate.execute(batch);
}
 
开发者ID:Mert-Z,项目名称:spring-oauth2-cassandra-token-store,代码行数:32,代码来源:CassandraTokenStore.java

示例14: insertTimeline

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
private boolean insertTimeline(XmTimeline xmTimeline, String table) {
    Insert insert = QueryBuilder.insertInto(xmTimeline.getTenant(), table)
        .value(LOGIN_COL, xmTimeline.getLogin())
        .value(USER_KEY_COL, xmTimeline.getUserKey())
        .value(START_DATE_COL, xmTimeline.getStartDate())
        .value(RID_COL, xmTimeline.getRid())
        .value(TENANT_COL, xmTimeline.getTenant())
        .value(MS_NAME_COL, xmTimeline.getMsName())
        .value(OPERATION_COL, xmTimeline.getOperationName())
        .value(ENTITY_ID_COL, xmTimeline.getEntityId())
        .value(ENTITY_KEY_COL, xmTimeline.getEntityKey())
        .value(ENTITY_TYPE_KEY_COL, xmTimeline.getEntityTypeKey())
        .value(OPERATION_URL_COL, xmTimeline.getOperationUrl())
        .value(HTTP_METHOD_COL, xmTimeline.getHttpMethod())
        .value(REQUEST_BODY_COL, xmTimeline.getRequestBody())
        .value(REQUEST_LENGTH_COL, xmTimeline.getRequestLength())
        .value(RESPONSE_BODY_COL, xmTimeline.getResponseBody())
        .value(RESPONSE_LENGTH_COL, xmTimeline.getResponseLength())
        .value(REQUEST_HEADERS_COL, xmTimeline.getRequestHeaders())
        .value(RESPONSE_HEADERS_COL, xmTimeline.getResponseHeaders())
        .value(HTTP_STATUS_CODE_COL, xmTimeline.getHttpStatusCode())
        .value(CHANNEL_TYPE_COL, xmTimeline.getChannelType())
        .value(EXEC_TIME_COL, xmTimeline.getExecTime());

    ResultSet resultSet = session.execute(insert);
    return resultSet.wasApplied();
}
 
开发者ID:xm-online,项目名称:xm-ms-timeline,代码行数:28,代码来源:TimelineRepository.java

示例15: save

import com.datastax.driver.core.querybuilder.Insert; //导入依赖的package包/类
public void save(List<Event> events) {
    final BatchStatement batch = new BatchStatement();
    for (final Event event : events) {
        final Map<String, Object> parsedEvent = parse(event);
        if (parsedEvent.isEmpty()) {
            log.warn("Event {} could not be mapped", event);
            continue;
        }
        if (!hasPrimaryKey(parsedEvent)) {
            break;
        }
        final Insert insert = QueryBuilder.insertInto(table);
        for (final Map.Entry<String, Object> entry : parsedEvent.entrySet()) {
            insert.value(entry.getKey(), entry.getValue());
        }
        if (log.isTraceEnabled()) {
            log.trace("Preparing insert for table {}: {}", table.getName(), insert.getQueryString());
        }
        batch.add(insert);
    }
    if (batch.getStatements().isEmpty()) {
        log.warn("No event produced insert query for table {}", table.getName());
        return;
    }
    batch.setConsistencyLevel(consistencyLevel);
    session.execute(batch);
}
 
开发者ID:madbrain,项目名称:flume-examples,代码行数:28,代码来源:CassandraSink.java


注:本文中的com.datastax.driver.core.querybuilder.Insert类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。