CQL Template API

CqlTemplate 类(及其反应式变体 ReactiveCqlTemplate)是核心 CQL 包中的核心类。它处理资源的创建和释放。它执行核心 CQL 工作流的基本任务,例如语句创建和执行,并留待应用程序代码提供 CQL 并提取结果。 CqlTemplate 类执行 CQL 查询和更新语句,对 ResultSet 实例进行迭代,并提取返回的参数值。它还会捕获 CQL 异常,并将它们转换为在 org.springframework.dao 包中定义的通用、更多的信息性异常层次结构。 当您将 CqlTemplate`用于您的代码时,您只需实现具有明确定义的契约的回调接口。给定 `ConnectionPreparedStatementCreator`回调接口将使用提供的 CQL 和任何必需的参数创建一个 prepared statement。`RowCallbackHandler`接口从 `ResultSet`的每一行中提取值。 `CqlTemplate 可在 DAO 实现中直接通过包含 SessionFactory 引用的实例化使用,或者在 Spring 容器中进行配置并作为 Bean 引用提供给 DAO。CqlTemplateCassandraTemplate 的基础构建块。 此类发出的所有 CQL 都在与模板实例的全限定类名(通常为 CqlTemplate,但如果您使用 CqlTemplate 类的自定义子类,可能有所不同)对应的类目下以 DEBUG 级别记录。 您可以通过配置 CQL API 实例(CqlTemplateAsyncCqlTemplateReactiveCqlTemplate)上的这些参数来控制获取大小、一致性级别和重试策略的默认值。如果没有设置特定查询选项,则应用默认设置。

CqlTemplate 提供不同的执行模型风格。基本的 CqlTemplate 使用阻塞执行模型。你可以使用 AsyncCqlTemplate 进行异步执行并与 ListenableFuture 实例或 ReactiveCqlTemplate 进行同步,也可以使用它进行响应式执行。

Examples of CqlTemplate Class Usage

此部分提供了一些关于 `CqlTemplate`类在实际使用中的示例。这些示例并非 `CqlTemplate`公开的所有功能的详尽列表。有关该内容,请参见 Javadoc

Querying (SELECT) with CqlTemplate

下面的查询获取表中的行数:

  • Imperative

  • Reactive

/*
 * Copyright 2020-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https:://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.CqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;
import org.springframework.data.cassandra.core.cql.generator.DropTableCqlGenerator;
import org.springframework.data.cassandra.core.cql.keyspace.DropTableSpecification;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class CqlTemplateExamples {

	private CqlTemplate cqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		int rowCount = cqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		int countOfActorsNamedJoe = cqlTemplate.queryForObject(
				"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		String lastName = cqlTemplate.queryForObject(
				"SELECT last_name FROM t_actor WHERE id = ?",
				String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Actor actor = cqlTemplate.queryForObject("SELECT first_name, last_name FROM t_actor WHERE id = ?",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				}, 1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		List<Actor> actors = cqlTemplate.query(
				"SELECT first_name, last_name FROM t_actor",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		List<String> lastNames = cqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	List<Actor> findAllActors() {
		return cqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void prepared() {
		long actorId = 1;

		// tag::insert[]
		cqlTemplate.execute(
				"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
				"Leonor", "Watling");
		// end::insert[]

		// tag::update[]
		cqlTemplate.execute(
				"UPDATE t_actor SET last_name = ? WHERE id = ?",
				"Banjo", 5276L);
		// end::update[]

		// tag::delete[]
		cqlTemplate.execute(
				"DELETE FROM t_actor WHERE id = ?",
				5276L);
		// end::delete[]
	}

	@Test
	void other() {
		// tag::other[]
		cqlTemplate.execute("CREATE TABLE test_table (id uuid primary key, event text)");

		DropTableSpecification dropper = DropTableSpecification.dropTable("test_table");
		String cql = DropTableCqlGenerator.toCql(dropper);

		cqlTemplate.execute(cql);
		// end::other[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}
/*
 * Copyright 2023-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.ReactiveCqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class ReactiveCqlTemplateExamples {

	private ReactiveCqlTemplate reactiveCqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		Mono<Integer> rowCount = reactiveCqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		Mono<Integer> countOfActorsNamedJoe = reactiveCqlTemplate.queryForObject(
			"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		Mono<String> lastName = reactiveCqlTemplate.queryForObject(
			"SELECT last_name FROM t_actor WHERE id = ?",
			String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Mono<Actor> actor = reactiveCqlTemplate.queryForObject(
			"SELECT first_name, last_name FROM t_actor WHERE id = ?",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}},
			1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		Flux<Actor> actors = reactiveCqlTemplate.query(
		"SELECT first_name, last_name FROM t_actor",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}
		});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		Flux<String> lastNames = reactiveCqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	Flux<Actor> findAllActors() {
		return reactiveCqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void insert() {

		// tag::insert[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
			"Leonor", "Watling");
		// end::insert[]
	}

	@Test
	void update() {
		// tag::update[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"UPDATE t_actor SET last_name = ? WHERE id = ?",
			"Banjo", 5276L);
		// end::update[]
	}

	@Test
	void delete() {
		long actorId = 1;

		// tag::delete[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"DELETE FROM actor WHERE id = ?",
			actorId);
		// end::delete[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}

以下查询使用绑定变量:

  • Imperative

  • Reactive

/*
 * Copyright 2020-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https:://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.CqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;
import org.springframework.data.cassandra.core.cql.generator.DropTableCqlGenerator;
import org.springframework.data.cassandra.core.cql.keyspace.DropTableSpecification;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class CqlTemplateExamples {

	private CqlTemplate cqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		int rowCount = cqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		int countOfActorsNamedJoe = cqlTemplate.queryForObject(
				"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		String lastName = cqlTemplate.queryForObject(
				"SELECT last_name FROM t_actor WHERE id = ?",
				String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Actor actor = cqlTemplate.queryForObject("SELECT first_name, last_name FROM t_actor WHERE id = ?",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				}, 1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		List<Actor> actors = cqlTemplate.query(
				"SELECT first_name, last_name FROM t_actor",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		List<String> lastNames = cqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	List<Actor> findAllActors() {
		return cqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void prepared() {
		long actorId = 1;

		// tag::insert[]
		cqlTemplate.execute(
				"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
				"Leonor", "Watling");
		// end::insert[]

		// tag::update[]
		cqlTemplate.execute(
				"UPDATE t_actor SET last_name = ? WHERE id = ?",
				"Banjo", 5276L);
		// end::update[]

		// tag::delete[]
		cqlTemplate.execute(
				"DELETE FROM t_actor WHERE id = ?",
				5276L);
		// end::delete[]
	}

	@Test
	void other() {
		// tag::other[]
		cqlTemplate.execute("CREATE TABLE test_table (id uuid primary key, event text)");

		DropTableSpecification dropper = DropTableSpecification.dropTable("test_table");
		String cql = DropTableCqlGenerator.toCql(dropper);

		cqlTemplate.execute(cql);
		// end::other[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}
/*
 * Copyright 2023-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.ReactiveCqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class ReactiveCqlTemplateExamples {

	private ReactiveCqlTemplate reactiveCqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		Mono<Integer> rowCount = reactiveCqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		Mono<Integer> countOfActorsNamedJoe = reactiveCqlTemplate.queryForObject(
			"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		Mono<String> lastName = reactiveCqlTemplate.queryForObject(
			"SELECT last_name FROM t_actor WHERE id = ?",
			String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Mono<Actor> actor = reactiveCqlTemplate.queryForObject(
			"SELECT first_name, last_name FROM t_actor WHERE id = ?",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}},
			1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		Flux<Actor> actors = reactiveCqlTemplate.query(
		"SELECT first_name, last_name FROM t_actor",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}
		});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		Flux<String> lastNames = reactiveCqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	Flux<Actor> findAllActors() {
		return reactiveCqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void insert() {

		// tag::insert[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
			"Leonor", "Watling");
		// end::insert[]
	}

	@Test
	void update() {
		// tag::update[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"UPDATE t_actor SET last_name = ? WHERE id = ?",
			"Banjo", 5276L);
		// end::update[]
	}

	@Test
	void delete() {
		long actorId = 1;

		// tag::delete[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"DELETE FROM actor WHERE id = ?",
			actorId);
		// end::delete[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}

以下示例查询 String

  • Imperative

  • Reactive

/*
 * Copyright 2020-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https:://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.CqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;
import org.springframework.data.cassandra.core.cql.generator.DropTableCqlGenerator;
import org.springframework.data.cassandra.core.cql.keyspace.DropTableSpecification;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class CqlTemplateExamples {

	private CqlTemplate cqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		int rowCount = cqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		int countOfActorsNamedJoe = cqlTemplate.queryForObject(
				"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		String lastName = cqlTemplate.queryForObject(
				"SELECT last_name FROM t_actor WHERE id = ?",
				String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Actor actor = cqlTemplate.queryForObject("SELECT first_name, last_name FROM t_actor WHERE id = ?",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				}, 1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		List<Actor> actors = cqlTemplate.query(
				"SELECT first_name, last_name FROM t_actor",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		List<String> lastNames = cqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	List<Actor> findAllActors() {
		return cqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void prepared() {
		long actorId = 1;

		// tag::insert[]
		cqlTemplate.execute(
				"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
				"Leonor", "Watling");
		// end::insert[]

		// tag::update[]
		cqlTemplate.execute(
				"UPDATE t_actor SET last_name = ? WHERE id = ?",
				"Banjo", 5276L);
		// end::update[]

		// tag::delete[]
		cqlTemplate.execute(
				"DELETE FROM t_actor WHERE id = ?",
				5276L);
		// end::delete[]
	}

	@Test
	void other() {
		// tag::other[]
		cqlTemplate.execute("CREATE TABLE test_table (id uuid primary key, event text)");

		DropTableSpecification dropper = DropTableSpecification.dropTable("test_table");
		String cql = DropTableCqlGenerator.toCql(dropper);

		cqlTemplate.execute(cql);
		// end::other[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}
/*
 * Copyright 2023-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.ReactiveCqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class ReactiveCqlTemplateExamples {

	private ReactiveCqlTemplate reactiveCqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		Mono<Integer> rowCount = reactiveCqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		Mono<Integer> countOfActorsNamedJoe = reactiveCqlTemplate.queryForObject(
			"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		Mono<String> lastName = reactiveCqlTemplate.queryForObject(
			"SELECT last_name FROM t_actor WHERE id = ?",
			String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Mono<Actor> actor = reactiveCqlTemplate.queryForObject(
			"SELECT first_name, last_name FROM t_actor WHERE id = ?",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}},
			1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		Flux<Actor> actors = reactiveCqlTemplate.query(
		"SELECT first_name, last_name FROM t_actor",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}
		});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		Flux<String> lastNames = reactiveCqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	Flux<Actor> findAllActors() {
		return reactiveCqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void insert() {

		// tag::insert[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
			"Leonor", "Watling");
		// end::insert[]
	}

	@Test
	void update() {
		// tag::update[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"UPDATE t_actor SET last_name = ? WHERE id = ?",
			"Banjo", 5276L);
		// end::update[]
	}

	@Test
	void delete() {
		long actorId = 1;

		// tag::delete[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"DELETE FROM actor WHERE id = ?",
			actorId);
		// end::delete[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}

以下示例查询并填充单个域对象:

  • Imperative

  • Reactive

/*
 * Copyright 2020-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https:://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.CqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;
import org.springframework.data.cassandra.core.cql.generator.DropTableCqlGenerator;
import org.springframework.data.cassandra.core.cql.keyspace.DropTableSpecification;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class CqlTemplateExamples {

	private CqlTemplate cqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		int rowCount = cqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		int countOfActorsNamedJoe = cqlTemplate.queryForObject(
				"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		String lastName = cqlTemplate.queryForObject(
				"SELECT last_name FROM t_actor WHERE id = ?",
				String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Actor actor = cqlTemplate.queryForObject("SELECT first_name, last_name FROM t_actor WHERE id = ?",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				}, 1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		List<Actor> actors = cqlTemplate.query(
				"SELECT first_name, last_name FROM t_actor",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		List<String> lastNames = cqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	List<Actor> findAllActors() {
		return cqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void prepared() {
		long actorId = 1;

		// tag::insert[]
		cqlTemplate.execute(
				"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
				"Leonor", "Watling");
		// end::insert[]

		// tag::update[]
		cqlTemplate.execute(
				"UPDATE t_actor SET last_name = ? WHERE id = ?",
				"Banjo", 5276L);
		// end::update[]

		// tag::delete[]
		cqlTemplate.execute(
				"DELETE FROM t_actor WHERE id = ?",
				5276L);
		// end::delete[]
	}

	@Test
	void other() {
		// tag::other[]
		cqlTemplate.execute("CREATE TABLE test_table (id uuid primary key, event text)");

		DropTableSpecification dropper = DropTableSpecification.dropTable("test_table");
		String cql = DropTableCqlGenerator.toCql(dropper);

		cqlTemplate.execute(cql);
		// end::other[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}
/*
 * Copyright 2023-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.ReactiveCqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class ReactiveCqlTemplateExamples {

	private ReactiveCqlTemplate reactiveCqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		Mono<Integer> rowCount = reactiveCqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		Mono<Integer> countOfActorsNamedJoe = reactiveCqlTemplate.queryForObject(
			"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		Mono<String> lastName = reactiveCqlTemplate.queryForObject(
			"SELECT last_name FROM t_actor WHERE id = ?",
			String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Mono<Actor> actor = reactiveCqlTemplate.queryForObject(
			"SELECT first_name, last_name FROM t_actor WHERE id = ?",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}},
			1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		Flux<Actor> actors = reactiveCqlTemplate.query(
		"SELECT first_name, last_name FROM t_actor",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}
		});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		Flux<String> lastNames = reactiveCqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	Flux<Actor> findAllActors() {
		return reactiveCqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void insert() {

		// tag::insert[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
			"Leonor", "Watling");
		// end::insert[]
	}

	@Test
	void update() {
		// tag::update[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"UPDATE t_actor SET last_name = ? WHERE id = ?",
			"Banjo", 5276L);
		// end::update[]
	}

	@Test
	void delete() {
		long actorId = 1;

		// tag::delete[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"DELETE FROM actor WHERE id = ?",
			actorId);
		// end::delete[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}

以下示例查询并填充多个域对象:

  • Imperative

  • Reactive

/*
 * Copyright 2020-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https:://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.CqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;
import org.springframework.data.cassandra.core.cql.generator.DropTableCqlGenerator;
import org.springframework.data.cassandra.core.cql.keyspace.DropTableSpecification;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class CqlTemplateExamples {

	private CqlTemplate cqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		int rowCount = cqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		int countOfActorsNamedJoe = cqlTemplate.queryForObject(
				"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		String lastName = cqlTemplate.queryForObject(
				"SELECT last_name FROM t_actor WHERE id = ?",
				String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Actor actor = cqlTemplate.queryForObject("SELECT first_name, last_name FROM t_actor WHERE id = ?",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				}, 1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		List<Actor> actors = cqlTemplate.query(
				"SELECT first_name, last_name FROM t_actor",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		List<String> lastNames = cqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	List<Actor> findAllActors() {
		return cqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void prepared() {
		long actorId = 1;

		// tag::insert[]
		cqlTemplate.execute(
				"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
				"Leonor", "Watling");
		// end::insert[]

		// tag::update[]
		cqlTemplate.execute(
				"UPDATE t_actor SET last_name = ? WHERE id = ?",
				"Banjo", 5276L);
		// end::update[]

		// tag::delete[]
		cqlTemplate.execute(
				"DELETE FROM t_actor WHERE id = ?",
				5276L);
		// end::delete[]
	}

	@Test
	void other() {
		// tag::other[]
		cqlTemplate.execute("CREATE TABLE test_table (id uuid primary key, event text)");

		DropTableSpecification dropper = DropTableSpecification.dropTable("test_table");
		String cql = DropTableCqlGenerator.toCql(dropper);

		cqlTemplate.execute(cql);
		// end::other[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}
/*
 * Copyright 2023-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.ReactiveCqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class ReactiveCqlTemplateExamples {

	private ReactiveCqlTemplate reactiveCqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		Mono<Integer> rowCount = reactiveCqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		Mono<Integer> countOfActorsNamedJoe = reactiveCqlTemplate.queryForObject(
			"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		Mono<String> lastName = reactiveCqlTemplate.queryForObject(
			"SELECT last_name FROM t_actor WHERE id = ?",
			String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Mono<Actor> actor = reactiveCqlTemplate.queryForObject(
			"SELECT first_name, last_name FROM t_actor WHERE id = ?",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}},
			1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		Flux<Actor> actors = reactiveCqlTemplate.query(
		"SELECT first_name, last_name FROM t_actor",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}
		});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		Flux<String> lastNames = reactiveCqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	Flux<Actor> findAllActors() {
		return reactiveCqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void insert() {

		// tag::insert[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
			"Leonor", "Watling");
		// end::insert[]
	}

	@Test
	void update() {
		// tag::update[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"UPDATE t_actor SET last_name = ? WHERE id = ?",
			"Banjo", 5276L);
		// end::update[]
	}

	@Test
	void delete() {
		long actorId = 1;

		// tag::delete[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"DELETE FROM actor WHERE id = ?",
			actorId);
		// end::delete[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}

如果最后两个代码片断实际上存在于同一个应用程序中,那么消除两个 RowMapper 匿名内部类中存在的重复并将其提取到一个可以由 DAO 方法引用的单个类(通常是 static 嵌套类)中是有意义的。

例如,最好将最后一个代码片断写成如下形式:

  • Imperative

  • Reactive

/*
 * Copyright 2020-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https:://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.CqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;
import org.springframework.data.cassandra.core.cql.generator.DropTableCqlGenerator;
import org.springframework.data.cassandra.core.cql.keyspace.DropTableSpecification;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class CqlTemplateExamples {

	private CqlTemplate cqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		int rowCount = cqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		int countOfActorsNamedJoe = cqlTemplate.queryForObject(
				"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		String lastName = cqlTemplate.queryForObject(
				"SELECT last_name FROM t_actor WHERE id = ?",
				String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Actor actor = cqlTemplate.queryForObject("SELECT first_name, last_name FROM t_actor WHERE id = ?",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				}, 1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		List<Actor> actors = cqlTemplate.query(
				"SELECT first_name, last_name FROM t_actor",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		List<String> lastNames = cqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	List<Actor> findAllActors() {
		return cqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void prepared() {
		long actorId = 1;

		// tag::insert[]
		cqlTemplate.execute(
				"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
				"Leonor", "Watling");
		// end::insert[]

		// tag::update[]
		cqlTemplate.execute(
				"UPDATE t_actor SET last_name = ? WHERE id = ?",
				"Banjo", 5276L);
		// end::update[]

		// tag::delete[]
		cqlTemplate.execute(
				"DELETE FROM t_actor WHERE id = ?",
				5276L);
		// end::delete[]
	}

	@Test
	void other() {
		// tag::other[]
		cqlTemplate.execute("CREATE TABLE test_table (id uuid primary key, event text)");

		DropTableSpecification dropper = DropTableSpecification.dropTable("test_table");
		String cql = DropTableCqlGenerator.toCql(dropper);

		cqlTemplate.execute(cql);
		// end::other[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}
/*
 * Copyright 2023-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.ReactiveCqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class ReactiveCqlTemplateExamples {

	private ReactiveCqlTemplate reactiveCqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		Mono<Integer> rowCount = reactiveCqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		Mono<Integer> countOfActorsNamedJoe = reactiveCqlTemplate.queryForObject(
			"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		Mono<String> lastName = reactiveCqlTemplate.queryForObject(
			"SELECT last_name FROM t_actor WHERE id = ?",
			String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Mono<Actor> actor = reactiveCqlTemplate.queryForObject(
			"SELECT first_name, last_name FROM t_actor WHERE id = ?",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}},
			1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		Flux<Actor> actors = reactiveCqlTemplate.query(
		"SELECT first_name, last_name FROM t_actor",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}
		});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		Flux<String> lastNames = reactiveCqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	Flux<Actor> findAllActors() {
		return reactiveCqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void insert() {

		// tag::insert[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
			"Leonor", "Watling");
		// end::insert[]
	}

	@Test
	void update() {
		// tag::update[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"UPDATE t_actor SET last_name = ? WHERE id = ?",
			"Banjo", 5276L);
		// end::update[]
	}

	@Test
	void delete() {
		long actorId = 1;

		// tag::delete[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"DELETE FROM actor WHERE id = ?",
			actorId);
		// end::delete[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}

INSERT, UPDATE, and DELETE with CqlTemplate

您可以使用 execute(…) 方法执行 INSERTUPDATEDELETE 操作。参数值通常以可变参数或对象数组的形式提供。

以下示例展示如何使用 CqlTemplate 执行 INSERT 操作:

  • Imperative

  • Reactive

/*
 * Copyright 2020-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https:://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.CqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;
import org.springframework.data.cassandra.core.cql.generator.DropTableCqlGenerator;
import org.springframework.data.cassandra.core.cql.keyspace.DropTableSpecification;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class CqlTemplateExamples {

	private CqlTemplate cqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		int rowCount = cqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		int countOfActorsNamedJoe = cqlTemplate.queryForObject(
				"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		String lastName = cqlTemplate.queryForObject(
				"SELECT last_name FROM t_actor WHERE id = ?",
				String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Actor actor = cqlTemplate.queryForObject("SELECT first_name, last_name FROM t_actor WHERE id = ?",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				}, 1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		List<Actor> actors = cqlTemplate.query(
				"SELECT first_name, last_name FROM t_actor",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		List<String> lastNames = cqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	List<Actor> findAllActors() {
		return cqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void prepared() {
		long actorId = 1;

		// tag::insert[]
		cqlTemplate.execute(
				"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
				"Leonor", "Watling");
		// end::insert[]

		// tag::update[]
		cqlTemplate.execute(
				"UPDATE t_actor SET last_name = ? WHERE id = ?",
				"Banjo", 5276L);
		// end::update[]

		// tag::delete[]
		cqlTemplate.execute(
				"DELETE FROM t_actor WHERE id = ?",
				5276L);
		// end::delete[]
	}

	@Test
	void other() {
		// tag::other[]
		cqlTemplate.execute("CREATE TABLE test_table (id uuid primary key, event text)");

		DropTableSpecification dropper = DropTableSpecification.dropTable("test_table");
		String cql = DropTableCqlGenerator.toCql(dropper);

		cqlTemplate.execute(cql);
		// end::other[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}
/*
 * Copyright 2023-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.ReactiveCqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class ReactiveCqlTemplateExamples {

	private ReactiveCqlTemplate reactiveCqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		Mono<Integer> rowCount = reactiveCqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		Mono<Integer> countOfActorsNamedJoe = reactiveCqlTemplate.queryForObject(
			"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		Mono<String> lastName = reactiveCqlTemplate.queryForObject(
			"SELECT last_name FROM t_actor WHERE id = ?",
			String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Mono<Actor> actor = reactiveCqlTemplate.queryForObject(
			"SELECT first_name, last_name FROM t_actor WHERE id = ?",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}},
			1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		Flux<Actor> actors = reactiveCqlTemplate.query(
		"SELECT first_name, last_name FROM t_actor",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}
		});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		Flux<String> lastNames = reactiveCqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	Flux<Actor> findAllActors() {
		return reactiveCqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void insert() {

		// tag::insert[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
			"Leonor", "Watling");
		// end::insert[]
	}

	@Test
	void update() {
		// tag::update[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"UPDATE t_actor SET last_name = ? WHERE id = ?",
			"Banjo", 5276L);
		// end::update[]
	}

	@Test
	void delete() {
		long actorId = 1;

		// tag::delete[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"DELETE FROM actor WHERE id = ?",
			actorId);
		// end::delete[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}

以下示例展示如何使用 CqlTemplate 执行 UPDATE 操作:

  • Imperative

  • Reactive

/*
 * Copyright 2020-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https:://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.CqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;
import org.springframework.data.cassandra.core.cql.generator.DropTableCqlGenerator;
import org.springframework.data.cassandra.core.cql.keyspace.DropTableSpecification;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class CqlTemplateExamples {

	private CqlTemplate cqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		int rowCount = cqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		int countOfActorsNamedJoe = cqlTemplate.queryForObject(
				"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		String lastName = cqlTemplate.queryForObject(
				"SELECT last_name FROM t_actor WHERE id = ?",
				String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Actor actor = cqlTemplate.queryForObject("SELECT first_name, last_name FROM t_actor WHERE id = ?",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				}, 1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		List<Actor> actors = cqlTemplate.query(
				"SELECT first_name, last_name FROM t_actor",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		List<String> lastNames = cqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	List<Actor> findAllActors() {
		return cqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void prepared() {
		long actorId = 1;

		// tag::insert[]
		cqlTemplate.execute(
				"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
				"Leonor", "Watling");
		// end::insert[]

		// tag::update[]
		cqlTemplate.execute(
				"UPDATE t_actor SET last_name = ? WHERE id = ?",
				"Banjo", 5276L);
		// end::update[]

		// tag::delete[]
		cqlTemplate.execute(
				"DELETE FROM t_actor WHERE id = ?",
				5276L);
		// end::delete[]
	}

	@Test
	void other() {
		// tag::other[]
		cqlTemplate.execute("CREATE TABLE test_table (id uuid primary key, event text)");

		DropTableSpecification dropper = DropTableSpecification.dropTable("test_table");
		String cql = DropTableCqlGenerator.toCql(dropper);

		cqlTemplate.execute(cql);
		// end::other[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}
/*
 * Copyright 2023-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.ReactiveCqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class ReactiveCqlTemplateExamples {

	private ReactiveCqlTemplate reactiveCqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		Mono<Integer> rowCount = reactiveCqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		Mono<Integer> countOfActorsNamedJoe = reactiveCqlTemplate.queryForObject(
			"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		Mono<String> lastName = reactiveCqlTemplate.queryForObject(
			"SELECT last_name FROM t_actor WHERE id = ?",
			String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Mono<Actor> actor = reactiveCqlTemplate.queryForObject(
			"SELECT first_name, last_name FROM t_actor WHERE id = ?",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}},
			1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		Flux<Actor> actors = reactiveCqlTemplate.query(
		"SELECT first_name, last_name FROM t_actor",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}
		});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		Flux<String> lastNames = reactiveCqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	Flux<Actor> findAllActors() {
		return reactiveCqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void insert() {

		// tag::insert[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
			"Leonor", "Watling");
		// end::insert[]
	}

	@Test
	void update() {
		// tag::update[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"UPDATE t_actor SET last_name = ? WHERE id = ?",
			"Banjo", 5276L);
		// end::update[]
	}

	@Test
	void delete() {
		long actorId = 1;

		// tag::delete[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"DELETE FROM actor WHERE id = ?",
			actorId);
		// end::delete[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}

下面的示例演示如何使用 CqlTemplate 执行 DELETE 操作:

  • Imperative

  • Reactive

/*
 * Copyright 2020-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https:://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.CqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;
import org.springframework.data.cassandra.core.cql.generator.DropTableCqlGenerator;
import org.springframework.data.cassandra.core.cql.keyspace.DropTableSpecification;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class CqlTemplateExamples {

	private CqlTemplate cqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		int rowCount = cqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		int countOfActorsNamedJoe = cqlTemplate.queryForObject(
				"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		String lastName = cqlTemplate.queryForObject(
				"SELECT last_name FROM t_actor WHERE id = ?",
				String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Actor actor = cqlTemplate.queryForObject("SELECT first_name, last_name FROM t_actor WHERE id = ?",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				}, 1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		List<Actor> actors = cqlTemplate.query(
				"SELECT first_name, last_name FROM t_actor",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		List<String> lastNames = cqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	List<Actor> findAllActors() {
		return cqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void prepared() {
		long actorId = 1;

		// tag::insert[]
		cqlTemplate.execute(
				"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
				"Leonor", "Watling");
		// end::insert[]

		// tag::update[]
		cqlTemplate.execute(
				"UPDATE t_actor SET last_name = ? WHERE id = ?",
				"Banjo", 5276L);
		// end::update[]

		// tag::delete[]
		cqlTemplate.execute(
				"DELETE FROM t_actor WHERE id = ?",
				5276L);
		// end::delete[]
	}

	@Test
	void other() {
		// tag::other[]
		cqlTemplate.execute("CREATE TABLE test_table (id uuid primary key, event text)");

		DropTableSpecification dropper = DropTableSpecification.dropTable("test_table");
		String cql = DropTableCqlGenerator.toCql(dropper);

		cqlTemplate.execute(cql);
		// end::other[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}
/*
 * Copyright 2023-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.ReactiveCqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class ReactiveCqlTemplateExamples {

	private ReactiveCqlTemplate reactiveCqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		Mono<Integer> rowCount = reactiveCqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		Mono<Integer> countOfActorsNamedJoe = reactiveCqlTemplate.queryForObject(
			"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		Mono<String> lastName = reactiveCqlTemplate.queryForObject(
			"SELECT last_name FROM t_actor WHERE id = ?",
			String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Mono<Actor> actor = reactiveCqlTemplate.queryForObject(
			"SELECT first_name, last_name FROM t_actor WHERE id = ?",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}},
			1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		Flux<Actor> actors = reactiveCqlTemplate.query(
		"SELECT first_name, last_name FROM t_actor",
			new RowMapper<Actor>() {
				public Actor mapRow(Row row, int rowNum) {
					Actor actor = new Actor();
					actor.setFirstName(row.getString("first_name"));
					actor.setLastName(row.getString("last_name"));
					return actor;
				}
		});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		Flux<String> lastNames = reactiveCqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	Flux<Actor> findAllActors() {
		return reactiveCqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void insert() {

		// tag::insert[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
			"Leonor", "Watling");
		// end::insert[]
	}

	@Test
	void update() {
		// tag::update[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"UPDATE t_actor SET last_name = ? WHERE id = ?",
			"Banjo", 5276L);
		// end::update[]
	}

	@Test
	void delete() {
		long actorId = 1;

		// tag::delete[]
		Mono<Boolean> applied = reactiveCqlTemplate.execute(
			"DELETE FROM actor WHERE id = ?",
			actorId);
		// end::delete[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}

Other CqlTemplate operations

你可以使用 execute(..) 方法来执行任何任意的 CQL,结果是,该方法通常用于 DDL 语句,它被大量重载,其中使用了采用回调接口、绑定变量阵列等方法的变体。

下面的示例演示如何使用传递给 execute() 方法的所有不同的 API 对象来创建和删除表:

/*
 * Copyright 2020-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https:://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.data.cassandra.example;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.data.cassandra.core.cql.CqlTemplate;
import org.springframework.data.cassandra.core.cql.RowMapper;
import org.springframework.data.cassandra.core.cql.generator.DropTableCqlGenerator;
import org.springframework.data.cassandra.core.cql.keyspace.DropTableSpecification;

import com.datastax.oss.driver.api.core.cql.Row;

/**
 * @author Mark Paluch
 */
//@formatter:off
public class CqlTemplateExamples {

	private CqlTemplate cqlTemplate = null;

	void examples() {
		// tag::rowCount[]
		int rowCount = cqlTemplate.queryForObject("SELECT COUNT(*) FROM t_actor", Integer.class);
		// end::rowCount[]

		// tag::countOfActorsNamedJoe[]
		int countOfActorsNamedJoe = cqlTemplate.queryForObject(
				"SELECT COUNT(*) FROM t_actor WHERE first_name = ?", Integer.class, "Joe");
		// end::countOfActorsNamedJoe[]

		// tag::lastName[]
		String lastName = cqlTemplate.queryForObject(
				"SELECT last_name FROM t_actor WHERE id = ?",
				String.class, 1212L);
		// end::lastName[]

		// tag::rowMapper[]
		Actor actor = cqlTemplate.queryForObject("SELECT first_name, last_name FROM t_actor WHERE id = ?",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				}, 1212L);
		// end::rowMapper[]

		// tag::listOfRowMapper[]
		List<Actor> actors = cqlTemplate.query(
				"SELECT first_name, last_name FROM t_actor",
				new RowMapper<Actor>() {
					public Actor mapRow(Row row, int rowNum) {
						Actor actor = new Actor();
						actor.setFirstName(row.getString("first_name"));
						actor.setLastName(row.getString("last_name"));
						return actor;
					}
				});
		// end::listOfRowMapper[]

		// tag::preparedStatement[]
		List<String> lastNames = cqlTemplate.query(
				session -> session.prepare("SELECT last_name FROM t_actor WHERE id = ?"),
				ps -> ps.bind(1212L),
				(row, rowNum) -> row.getString(0));
		// end::preparedStatement[]
	}

	// tag::findAllActors[]
	List<Actor> findAllActors() {
		return cqlTemplate.query("SELECT first_name, last_name FROM t_actor", ActorMapper.INSTANCE);
	}

	enum ActorMapper implements RowMapper<Actor> {

		INSTANCE;

		public Actor mapRow(Row row, int rowNum) {
			Actor actor = new Actor();
			actor.setFirstName(row.getString("first_name"));
			actor.setLastName(row.getString("last_name"));
			return actor;
		}
	}
	// end::findAllActors[]

	@Test
	void prepared() {
		long actorId = 1;

		// tag::insert[]
		cqlTemplate.execute(
				"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
				"Leonor", "Watling");
		// end::insert[]

		// tag::update[]
		cqlTemplate.execute(
				"UPDATE t_actor SET last_name = ? WHERE id = ?",
				"Banjo", 5276L);
		// end::update[]

		// tag::delete[]
		cqlTemplate.execute(
				"DELETE FROM t_actor WHERE id = ?",
				5276L);
		// end::delete[]
	}

	@Test
	void other() {
		// tag::other[]
		cqlTemplate.execute("CREATE TABLE test_table (id uuid primary key, event text)");

		DropTableSpecification dropper = DropTableSpecification.dropTable("test_table");
		String cql = DropTableCqlGenerator.toCql(dropper);

		cqlTemplate.execute(cql);
		// end::other[]
	}

	static class Actor {

		void setFirstName(String first_name) {

		}

		void setLastName(String last_name) {}
	}
}

Controlling Cassandra Connections

应用程序通过使用 CqlSession 对象连接到 Apache Cassandra,Cassandra CqlSession 跟踪跟单个节点的多个连接,旨在成为一个线程安全的长生存期对象,通常,你可以为整个应用程序使用一个单独的 CqlSession

Spring 通过 SessionFactory 获取一个 Cassandra CqlSessionSessionFactory 是 Spring Data for Apache Cassandra 的一部分,它是一个泛化的连接工厂,它让容器或框架对应用程序代码隐藏连接处理和路由问题。

下面的示例演示如何配置一个默认的 SessionFactory

  • Imperative

  • Reactive

CqlSession session = … // get a Cassandra Session

CqlTemplate template = new CqlTemplate();

template.setSessionFactory(new DefaultSessionFactory(session));
CqlSession session = … // get a Cassandra Session

ReactiveCqlTemplate template = new ReactiveCqlTemplate(new DefaultBridgedReactiveSession(session));

CqlTemplate 和其他模板 API 实现为每个操作获取一个 CqlSession,由于它们长期存在的性质,在调用所需操作后,会话不会被关闭,正确资源释放的职责在于使用该会话的容器或框架。

你可以在 org.springframework.data.cassandra.core.cql.session 包中找到 diverse SessionFactory 实现。

Exception Translation

Spring Framework 为各种不同的数据库和映射技术提供异常转换,这些技术传统上是 JDBC 和 JPA,Spring Data for Apache Cassandra 通过提供 org.springframework.dao.support.PersistenceExceptionTranslator 接口的实现来将这个特性扩展到 Apache Cassandra。

映射到 Spring 的 一致的数据访问异常层级 的动机是让您编写可移植且描述性的异常处理代码,而无需诉诸于与特定 Cassandra 异常进行编码和处理。Spring 的所有数据访问异常均继承自 DataAccessException 类,因此,您可确保在单个 try-catch 块内捕获所有与数据库相关异常。

ReactiveCqlTemplateReactiveCassandraTemplate 尽早传播异常,在处理响应式序列期间发生的异常作为错误信号发出。