本文整理汇总了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)));
}
示例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();
}
}
示例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;
}
示例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();
}
示例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()));
}
示例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");
}
示例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");
}
示例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();
}
}
示例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 );
}
示例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 );
}
示例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 );
}
示例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;
}
示例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);
}
示例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();
}
示例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);
}