### Example Repository Interface Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/aot.adoc This is an example of a Spring Data Cassandra repository interface with a simple query method. ```java interface UserRepository extends CrudRepository { List findUserNoArgumentsBy(); <1> ``` -------------------------------- ### List of Row Mappers Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Example demonstrating how to use a list of RowMappers with CqlTemplate. ```java List> actors = listOfRowMapper(); ``` -------------------------------- ### Configure Default SessionFactory Imperative Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Example of configuring a default SessionFactory for CqlTemplate. ```java CqlSession session = CqlTemplate template = new CqlTemplate(); template.setSessionFactory(new DefaultSessionFactory(session)); ``` -------------------------------- ### Configure Default SessionFactory Reactive Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Example of configuring a default SessionFactory for ReactiveCqlTemplate. ```java CqlSession session = ReactiveCqlTemplate template = new ReactiveCqlTemplate(new DefaultBridgedReactiveSession(session)); ``` -------------------------------- ### Build Spring Data Cassandra from Source Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/README.adoc Use the Maven wrapper to clean and install the project from source. Requires JDK 17. ```bash $ ./mvnw clean install ``` -------------------------------- ### Other CqlTemplate Operations Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Example demonstrating arbitrary CQL execution for DDL statements using CqlTemplate. ```java template.execute(cqlSession -> cqlSession.execute("CREATE TABLE IF NOT EXISTS " + tableName + " (") ); template.execute(cqlSession -> cqlSession.execute("DROP TABLE IF EXISTS " + tableName) ); ``` -------------------------------- ### Create Update for Setting a Key Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/template.adoc Example of creating an Update object to set a specific key to a string value. ```java // UPDATE … SET key = 'Spring Data'; Update.update("key", "Spring Data") ``` -------------------------------- ### Configuration Class for Cassandra Mapping Support Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/object-mapping.adoc An example of a @Configuration class that sets up Cassandra mapping support, including scanning for domain classes and registering custom converters. ```java include::example$SchemaConfiguration.java[tags=class] ``` -------------------------------- ### Query Multiple Domain Objects with CqlTemplate Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Queries and populates multiple domain objects using CqlTemplate. This example retrieves a list of domain objects from query results. ```java List actors = cqlTemplate.query("SELECT * FROM actors WHERE first_name = ?", new ActorRowMapper(), "Scarlett"); ``` -------------------------------- ### Query Multiple Domain Objects with ReactiveCqlTemplate Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Queries and populates multiple domain objects using ReactiveCqlTemplate. This example retrieves a list of domain objects reactively. ```java List actors = reactiveCqlTemplate.query("SELECT * FROM actors WHERE first_name = ?", new ActorRowMapper(), "Scarlett").collectList().block(); ``` -------------------------------- ### Find All Actors Imperative Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Example of finding all actors using CqlTemplate in an imperative style. ```java List actors = template.queryForList("SELECT * FROM actor", Actor.class); return actors; ``` -------------------------------- ### Insert Operation Imperative Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Example of performing an INSERT operation with CqlTemplate. ```java template.execute("INSERT INTO actor (actor_id, first_name, last_name) VALUES (?, ?, ?)", UUIDs.timeBased(), "Scarlett", "Johansson"); ``` -------------------------------- ### Vector Search Query Example Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/template.adoc Demonstrates how to perform a vector search query. It selects specific columns, includes a similarity function, defines the sort order using `VectorSort.ann`, and maps the results to a projection type (`CommentSearch`). ```java Columns columns = Columns.from("comment") <1> .select("vector", builder -> builder.similarity(vector) .cosine().as("similarity")); <2> Query query = Query.select(columns) .limit(3) .sort(VectorSort.ann("vector", vector)); <3> template.query(Comments.class) .as(CommentSearch.class) <4> .matching(query) .all(); ``` -------------------------------- ### Cassandra Query Method Keywords: After Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/query-methods.adoc Example of using the 'After' keyword for date-based queries in Cassandra repository methods. ```java findByBirthdateAfter(Date date) ``` -------------------------------- ### Query String with ReactiveCqlTemplate Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Queries for a String value using ReactiveCqlTemplate. This example retrieves a specific field reactively. ```java String lastName = reactiveCqlTemplate.queryForObject("SELECT last_name FROM actors WHERE first_name = ?", String.class, "Joe").block(); ``` -------------------------------- ### Find All Actors Reactive Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Example of finding all actors using ReactiveCqlTemplate in a reactive style. ```java Flux actors = reactiveTemplate.queryForFlux("SELECT * FROM actor", Actor.class); return actors; ``` -------------------------------- ### Query String with CqlTemplate Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Queries for a String value using CqlTemplate. This example retrieves a specific field from a row. ```java String lastName = cqlTemplate.queryForObject("SELECT last_name FROM actors WHERE first_name = ?", String.class, "Joe"); ``` -------------------------------- ### Enable Keyspace Initialization from System Property Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/schema-management.adoc Configure Cassandra keyspace initialization to be enabled or disabled based on a system property. This allows for environment-specific control over schema setup. ```xml <1> ``` -------------------------------- ### Update Operation Imperative Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Example of performing an UPDATE operation with CqlTemplate. ```java template.execute("UPDATE actor SET first_name = ? WHERE actor_id = ?", "Robert", actorId); ``` -------------------------------- ### Count Rows with CqlTemplate Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Counts the number of rows in a table using CqlTemplate. This example demonstrates a basic query execution. ```java long rowCount = cqlTemplate.queryForObject("SELECT count(*) FROM users", Long.class); ``` -------------------------------- ### Create Immutable QueryOptions with Builder Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/migration-guide/migration-guide-1.5-to-2.0.adoc Use `QueryOptions.builder()` to construct immutable `QueryOptions` objects. This example demonstrates setting consistency level, retry policy, read timeout, fetch size, and tracing. ```java QueryOptions queryOptions = QueryOptions.builder() .consistencyLevel(ConsistencyLevel.ANY) .retryPolicy(FallthroughRetryPolicy.INSTANCE) .readTimeout(Duration.ofSeconds(10)) .fetchSize(10) .tracing(true) .build(); ``` -------------------------------- ### Mapped User-Defined Type Address Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/object-mapping.adoc Example demonstrating how to map a User-Defined Type (UDT) named Address for use with Cassandra. ```java include::example$mapping/Address.java[tags=class] ``` -------------------------------- ### Derived Query with Pagination Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/aot.adoc Example of a derived query that utilizes pagination. The query string is normalized with a bind marker for the 'lastname' parameter. ```java Slice findSliceOfUsersByLastnameStartingWith(String lastname, Pageable page); ``` -------------------------------- ### Create Update for Setting Element at Index Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/template.adoc Example of creating an Update object to set an element at a specific index within a collection. ```java // UPDATE … SET key = key[5] = 'Spring Data'; Update.empty().set("key").atIndex(5).to("Spring Data"); ``` -------------------------------- ### Count Rows with ReactiveCqlTemplate Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Counts the number of rows in a table using ReactiveCqlTemplate. This example demonstrates reactive query execution. ```java long rowCount = reactiveCqlTemplate.queryForObject("SELECT count(*) FROM users", Long.class).block(); ``` -------------------------------- ### Configure Spring Data Cassandra with AbstractCassandraConfiguration Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/configuration.adoc Extend AbstractCassandraConfiguration to automatically register Spring Data for Apache Cassandra beans. This base class simplifies configuration by providing default setups for entities, query options, and pooling. ```java import org.springframework.context.annotation.Configuration; import org.springframework.data.cassandra.config.AbstractCassandraConfiguration; @Configuration public class CassandraConfiguration extends AbstractCassandraConfiguration { @Override protected String getKeyspaceName() { return "mykeyspace"; } } ``` -------------------------------- ### Build Reference Documentation Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/README.adoc Build the project documentation, which also builds the project without running tests. Requires the Antora profile. ```bash $ ./mvnw clean install -Pantora ``` -------------------------------- ### Get ReactiveCassandraTemplate Bean Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/template.adoc Retrieves the ReactiveCassandraTemplate bean from the ApplicationContext. ```java ReactiveCassandraOperations cassandraOperations = applicationContext.getBean("ReactiveCassandraOperations", ReactiveCassandraOperations.class); ``` -------------------------------- ### CassandraCustomConversions Configuration Sample Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/property-converters.adoc Provides a sample configuration for CassandraCustomConversions, demonstrating how to set up programmatic value conversions and define PropertyValueConverterFactory instances. ```java CassandraCustomConversions conversions = CassandraCustomConversions.create(adapter -> { adapter.registerConverter(…); adapter.configurePropertyConversions(registrar -> { registrar.registerConverter(Person.class, "name", String.class) .writing((from, ctx) -> …) .reading((from, ctx) -> …); }); }); ``` -------------------------------- ### Get CassandraTemplate Bean Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/template.adoc Retrieves the CassandraTemplate bean from the ApplicationContext. ```java CassandraOperations cassandraOperations = applicationContext.getBean("cassandraTemplate", CassandraOperations.class); ``` -------------------------------- ### Delete Operation Reactive Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Example of performing a DELETE operation with ReactiveCqlTemplate. ```java reactiveTemplate.execute("DELETE FROM actor WHERE actor_id = ?", actorId).subscribe(); ``` -------------------------------- ### Delete Operation Imperative Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Example of performing a DELETE operation with CqlTemplate. ```java template.execute("DELETE FROM actor WHERE actor_id = ?", actorId); ``` -------------------------------- ### Configure Cassandra Keyspace Creation (Java) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/schema-management.adoc Define a Cassandra keyspace with replication strategy and durable writes using Java configuration. ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.cassandra.SessionFactory; import org.springframework.data.cassandra.core.cql.session.init.KeyspacePopulator; import org.springframework.data.cassandra.core.cql.session.init.ResourceKeyspacePopulator; import java.util.Arrays; @Configuration public class CreateKeyspaceConfiguration { @Bean public KeyspacePopulator keyspacePopulator(SessionFactory sessionFactory) { ResourceKeyspacePopulator populator = new ResourceKeyspacePopulator(); populator.setScripts(Arrays.asList( new ClassPathResource("com/example/cassandra/cql/create-keyspace.cql"))); return populator; } } ``` -------------------------------- ### Update Operation Reactive Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Example of performing an UPDATE operation with ReactiveCqlTemplate. ```java reactiveTemplate.execute("UPDATE actor SET first_name = ? WHERE actor_id = ?", "Robert", actorId).subscribe(); ``` -------------------------------- ### Insert Operation Reactive Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Example of performing an INSERT operation with ReactiveCqlTemplate. ```java reactiveTemplate.execute("INSERT INTO actor (actor_id, first_name, last_name) VALUES (?, ?, ?)", UUIDs.timeBased(), "Scarlett", "Johansson").subscribe(); ``` -------------------------------- ### Use Prepared Statements with CassandraTemplate (Imperative) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/prepared-statements.adoc Demonstrates using prepared statements with `CassandraTemplate` in an imperative context. Prepared statements are enabled by default. ```java cassandraTemplate.execute("UPDATE user SET lastName = ?1 WHERE id = ?2", "Smith", UUID.randomUUID()); ``` -------------------------------- ### Imperative Java Configuration for Cassandra Repositories Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/repositories.adoc Configures Cassandra repositories using Java configuration with @EnableCassandraRepositories and AbstractCassandraConfiguration. ```java @Configuration @EnableCassandraRepositories class ApplicationConfig extends AbstractCassandraConfiguration { @Override protected String getKeyspaceName() { return "keyspace"; } public String[] getEntityBasePackages() { return new String[] { "com.oreilly.springdata.cassandra" }; } } ``` -------------------------------- ### Configure Cassandra Keyspace Creation (XML) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/schema-management.adoc Define a Cassandra keyspace with replication strategy and durable writes using XML configuration. ```xml ``` -------------------------------- ### Manual Prepared Statement Creation and Binding (Reactive) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/prepared-statements.adoc Control prepared statement creation and parameter binding manually using `PreparedStatementCreator` and `PreparedStatementBinder` with `ReactiveCqlTemplate`. This is suitable for reactive programming models. ```java reactiveCqlTemplate.execute(new SimplePreparedStatementCreator("UPDATE user SET lastName = ?1 WHERE id = ?2"), new ArgumentPreparedStatementBinder("Smith", UUID.randomUUID())); ``` -------------------------------- ### Manual Prepared Statement Creation and Binding (Imperative) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/prepared-statements.adoc Control prepared statement creation and parameter binding manually using `PreparedStatementCreator` and `PreparedStatementBinder` with `CqlTemplate`. This allows for advanced scenarios like named parameter binding. ```java cqlTemplate.execute(new SimplePreparedStatementCreator("UPDATE user SET lastName = ?1 WHERE id = ?2"), new ArgumentPreparedStatementBinder("Smith", UUID.randomUUID())); ``` -------------------------------- ### Configure Entity Base Packages in XML Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/schema-management.adoc Specify the base packages for Cassandra entities using XML configuration. Ensure the correct schema locations are defined. ```xml ``` -------------------------------- ### Initialize Keyspace with CQL Scripts (Java) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/schema-management.adoc Configure Spring Data Cassandra to execute CQL scripts on session initialization and shutdown using Java configuration. ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.cassandra.SessionFactory; import org.springframework.data.cassandra.core.cql.session.init.KeyspacePopulator; import org.springframework.data.cassandra.core.cql.session.init.ResourceKeyspacePopulator; import java.util.Arrays; @Configuration public class KeyspacePopulatorConfiguration { @Bean public KeyspacePopulator keyspacePopulator(SessionFactory sessionFactory) { ResourceKeyspacePopulator populator = new ResourceKeyspacePopulator(); populator.setScripts(Arrays.asList( new ClassPathResource("com/foo/cql/db-schema.cql"), new ClassPathResource("com/foo/cql/db-test-data.cql"))); return populator; } } ``` -------------------------------- ### Annotated Query Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/aot.adoc An example of an annotated query using @Query. The query string is normalized with a bind marker for the 'emailAddress' parameter. ```java User findAnnotatedQueryByEmailAddress(String emailAddress); ``` -------------------------------- ### Reactive Java Configuration for Cassandra Repositories Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/repositories.adoc Configures reactive Cassandra repositories using Java configuration with @EnableReactiveCassandraRepositories and AbstractReactiveCassandraConfiguration. ```java @Configuration @EnableReactiveCassandraRepositories class ApplicationConfig extends AbstractReactiveCassandraConfiguration { @Override protected String getKeyspaceName() { return "keyspace"; } public String[] getEntityBasePackages() { return new String[] { "com.oreilly.springdata.cassandra" }; } } ``` -------------------------------- ### Use Prepared Statements with ReactiveCassandraTemplate (Reactive) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/prepared-statements.adoc Demonstrates using prepared statements with `ReactiveCassandraTemplate` in a reactive context. Prepared statements are enabled by default. ```java reactiveCassandraTemplate.execute("UPDATE user SET lastName = ?1 WHERE id = ?2", "Smith", UUID.randomUUID()); ``` -------------------------------- ### Create Update for Appending Multiple Values to Collection Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/template.adoc Example of creating an Update object to append multiple values to an existing collection. ```java // UPDATE … SET key = key + ['Spring', 'DATA']; Update.empty().addTo("key").appendAll("Spring", "Data"); ``` -------------------------------- ### Entity with Various Indexing Strategies Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/object-mapping.adoc Demonstrates creating secondary indexes on different types of properties, including scalar, collection, and map entries, keys, or values. Use `@Indexed`, `@SASI`, `@StandardAnalyzed`, or `@NonTokenizingAnalyzed` as needed. ```java package example.mapping; import org.springframework.data.annotation.Id; import org.springframework.data.cassandra.core.mapping.*; import java.util.List; import java.util.Map; import java.util.Set; @Table public class PersonWithIndexes { @Id private final String name; @Indexed private final int age; @SASI(mode = SASI.Mode.CONTAINS, analyzed = @Analyzed(analyzerClass = org.apache.lucene.analysis.standard.StandardAnalyzer.class, language = org.apache.lucene.analysis.standard.StandardAnalyzer.class)) private final String description; @Indexed(target = IndexTarget.KEYS) private final Map keyIndexedMap; @Indexed(target = IndexTarget.VALUES) private final Map valueIndexedMap; @Indexed(target = IndexTarget.ENTRY) private final Map entryIndexedMap; @NonTokenizingAnalyzed private final String nonTokenizingDescription; private final Coordinates coordinates; @Indexed private final Set tags; @Indexed private final List list; @Embedded @Indexed private final Address address; public PersonWithIndexes(String name, int age, String description, Map keyIndexedMap, Map valueIndexedMap, Map entryIndexedMap, String nonTokenizingDescription, Coordinates coordinates, Set tags, List list, Address address) { this.name = name; this.age = age; this.description = description; this.keyIndexedMap = keyIndexedMap; this.valueIndexedMap = valueIndexedMap; this.entryIndexedMap = entryIndexedMap; this.nonTokenizingDescription = nonTokenizingDescription; this.coordinates = coordinates; this.tags = tags; this.list = list; this.address = address; } public String getName() { return name; } public int getAge() { return age; } public String getDescription() { return description; } public Map getKeyIndexedMap() { return keyIndexedMap; } public Map getValueIndexedMap() { return valueIndexedMap; } public Map getEntryIndexedMap() { return entryIndexedMap; } public String getNonTokenizingDescription() { return nonTokenizingDescription; } public Coordinates getCoordinates() { return coordinates; } public Set getTags() { return tags; } public List getList() { return list; } public Address getAddress() { return address; } } ``` -------------------------------- ### Initialize Keyspace with CQL Scripts (XML) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/schema-management.adoc Configure Spring Data Cassandra to execute CQL scripts on session initialization and shutdown using XML configuration. ```xml ``` -------------------------------- ### Mapped Person Class Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/object-mapping.adoc Example of a Person class mapped to a Cassandra table using various Spring Data Cassandra annotations. ```java include::example$mapping/Person.java[tags=class] ``` -------------------------------- ### Cassandra Query Method Keywords: GreaterThan Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/query-methods.adoc Example of using the 'GreaterThan' keyword for numeric range queries in Cassandra repository methods. ```java findByAgeGreaterThan(int age) ``` -------------------------------- ### Specify Cassandra Keyspace Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/schema-management.adoc Use the fluent API to build a specification for creating a Cassandra keyspace. ```java KeyspaceSpecification keyspace = SpecificationBuilder.keyspace("my_keyspace") .withReplicationFactor(1, "foo") .withReplicationFactor(2, "bar") .build(); ``` -------------------------------- ### Connect to Astra via AbstractCassandraConfiguration Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/configuration.adoc Customize CqlSession creation within AbstractCassandraConfiguration by providing a SessionBuilderConfigurer. This is useful for configuring Astra cloud connection bundles or other custom session settings. ```java import com.datastax.oss.driver.api.core.session.SessionBuilderConfigurer; import org.springframework.context.annotation.Configuration; import org.springframework.data.cassandra.config.AbstractCassandraConfiguration; @Configuration public class CustomizedCassandraConfiguration extends AbstractCassandraConfiguration { @Override protected String getKeyspaceName() { return "mykeyspace"; } @Override protected SessionBuilderConfigurer getSessionBuilderConfigurer() { return sessionBuilder -> sessionBuilder.withCloudSecureConnectBundle("/path/to/secure-connect-bundle.zip"); } } ``` -------------------------------- ### Execute Parametrized Query with CqlTemplate (Imperative) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/prepared-statements.adoc Use `CqlTemplate` to execute a query with a parametrized prepared statement. This method is suitable for imperative programming models. ```java cqlTemplate.execute("UPDATE user SET lastName = ?1 WHERE id = ?2", "Smith", UUID.randomUUID()); ``` -------------------------------- ### Cassandra Before Save Listener Example Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/events.adoc Implement `onBeforeSave` to intercept entity saving operations before they are persisted to the database. This listener is invoked after the `Statement` is created but before the entity is saved. ```java package example.mapping; import org.springframework.data.cassandra.core.mapping.event.AbstractCassandraEventListener; import org.springframework.data.cassandra.core.mapping.event.BeforeSaveEvent; import org.springframework.stereotype.Component; @Component public class BeforeSaveListener extends AbstractCassandraEventListener { @Override public void onBeforeSave(BeforeSaveEvent event) { System.out.println("Before save: " + event.getSource()); } } ``` -------------------------------- ### Call Repository Method for Vector Search Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/partials/vector-search-repository-include.adoc Shows how to invoke the defined repository method with appropriate parameters for vector search and retrieve results. ```java SearchResults results = repository.searchByEmbeddingNearAndCountry(Vector.of(…), ScoringFunction.cosine(), "…", Limit.of(10)); ``` -------------------------------- ### Execute Parametrized Query with ReactiveCqlTemplate (Reactive) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/prepared-statements.adoc Use `ReactiveCqlTemplate` to execute a query with a parametrized prepared statement. This method is suitable for reactive programming models. ```java reactiveCqlTemplate.execute("UPDATE user SET lastName = ?1 WHERE id = ?2", "Smith", UUID.randomUUID()); ``` -------------------------------- ### Maven Dependency: Apache Cassandra Driver (4.3+) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/migration-guide/migration-guide-4.0-to-4.3.adoc Illustrates the updated Maven dependency configuration for the Java driver starting from version 4.3, reflecting the groupId change to `org.apache.cassandra`. ```xml org.apache.cassandra java-driver-core org.apache.cassandra java-driver-query-builder ``` -------------------------------- ### Configuring NamingStrategy on CassandraMappingContext Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/object-mapping.adoc Shows how to configure a custom NamingStrategy on CassandraMappingContext to adjust conventions for deriving table and column names. ```java include::example$NamingStrategyConfiguration.java[tags=method] ``` -------------------------------- ### Example Domain Object with @Table and @Id Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/object-mapping.adoc Defines a simple domain object 'Person' annotated for Cassandra mapping. Use @Table to mark entities and @Id for the primary key field. ```java package com.mycompany.domain; @Table public class Person { @Id private String id; @CassandraType(type = Name.VARINT) private Integer ssn; private String firstName; private String lastName; } ``` -------------------------------- ### Reactive Paging Access to Person Entities Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/repositories.adoc Illustrates how to read pages of Person entities using reactive programming with Project Reactor. It fetches the first batch and then the subsequent batch. ```java @ExtendWith(SpringExtension.class) class PersonRepositoryTests { @Autowired PersonRepository repository; @Test void readsPagesCorrectly() { Mono> firstBatch = repository.findAll(CassandraPageRequest.first(10)); Mono> nextBatch = firstBatch.flatMap(it -> repository.findAll(it.nextPageable())); // … } }} ``` -------------------------------- ### Configure Observability for Cassandra Sessions Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/observability.adoc Apply this configuration to enable Micrometer instrumentation for both synchronous and reactive Cassandra sessions. It wraps the respective session builders with observation capabilities. ```java @Configuration class ObservabilityConfiguration { @Bean public ObservableCqlSessionFactoryBean observableCqlSession(CqlSessionBuilder builder, ObservationRegistry registry) { return new ObservableCqlSessionFactoryBean(builder, registry); // <1> } @Bean public ObservableReactiveSessionFactoryBean observableReactiveSession(CqlSession session, ObservationRegistry registry) { return new ObservableReactiveSessionFactoryBean(session, registry); // <2> } } ``` -------------------------------- ### Specify Cassandra Table Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/schema-management.adoc Use the fluent API to build a specification for creating a Cassandra table with primary keys and columns. ```java TableSpecification table = SpecificationBuilder.table("users") .partitionKeyColumn("id") .columns( new ColumnSpecification("name", DataType.text()), new ColumnSpecification("email", DataType.text()) ) .build(); ``` -------------------------------- ### XML Configuration for Cassandra Repositories Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/repositories.adoc Configures Cassandra repositories using XML, including session, mapping, converter, template, and repository beans. ```xml ``` -------------------------------- ### Ignore Failures During Keyspace Initialization Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/schema-management.adoc Configure the Cassandra keyspace initializer to ignore specific failures, such as 'DROP' statements, during script execution. This is useful when scripts might be run against an already populated keyspace. ```java include::example$KeyspacePopulatorFailureConfiguration.java[tags=class] ``` ```xml ``` -------------------------------- ### Cassandra Query Method with @Consistency (Imperative) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/query-methods.adoc Demonstrates setting a static consistency level for an imperative query method using the `@Consistency` annotation. The `LOCAL_ONE` level is applied on each execution. ```java interface PersonRepository extends CrudRepository { @Consistency(ConsistencyLevel.LOCAL_ONE) List findByLastname(String lastname); List findByFirstname(String firstname, QueryOptions options); } ``` -------------------------------- ### Cassandra Query Method with @Consistency (Reactive) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/query-methods.adoc Demonstrates setting a static consistency level for a reactive query method using the `@Consistency` annotation. The `LOCAL_ONE` level is applied on each execution. ```java interface PersonRepository extends ReactiveCrudRepository { @Consistency(ConsistencyLevel.LOCAL_ONE) Flux findByLastname(String lastname); Flux findByFirstname(String firstname, QueryOptions options); } ``` -------------------------------- ### Basic Access to Person Entities (Reactive) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/repositories.adoc Demonstrates basic access to Person entities using an injected ReactivePersonRepository in a reactive Spring context. ```java public class PersonRepositoryTests { @Autowired ReactivePersonRepository repository; ``` -------------------------------- ### Query Single Domain Object with ReactiveCqlTemplate Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Queries and populates a single domain object using ReactiveCqlTemplate and a RowMapper. This demonstrates reactive mapping of query results to a Java object. ```java Actor actor = reactiveCqlTemplate.queryForObject("SELECT * FROM actors WHERE first_name = ? AND last_name = ?", new ActorRowMapper(), "Scarlett", "Johansson").block(); ``` -------------------------------- ### Cassandra Properties Configuration Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/configuration.adoc Defines connection points and keyspace for Cassandra using properties. ```properties cassandra.contactpoints=10.1.55.80:9042,10.1.55.81:9042 cassandra.keyspace=showcase ``` -------------------------------- ### Execute Custom CQL Insert Imperatively Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/template.adoc Execute custom CQL statements directly using `getCqlOperations().execute()` for fine-grained control over insertion. ```java String cql = "INSERT INTO person (age, name) VALUES (39, 'Bob')"; cassandraTemplate().getCqlOperations().execute(cql); ``` -------------------------------- ### Query Single Domain Object with CqlTemplate Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/cql-template.adoc Queries and populates a single domain object using CqlTemplate and a RowMapper. This demonstrates mapping query results to a Java object. ```java Actor actor = cqlTemplate.queryForObject("SELECT * FROM actors WHERE first_name = ? AND last_name = ?", new ActorRowMapper(), "Scarlett", "Johansson"); ``` -------------------------------- ### Execute Custom CQL Insert Reactively Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/template.adoc Execute custom CQL statements directly using `getReactiveCqlOperations().execute()` for fine-grained control over reactive insertion. ```java String cql = "INSERT INTO person (age, name) VALUES (39, 'Bob')"; Mono applied = reactiveCassandraTemplate.getReactiveCqlOperations().execute(cql); ``` -------------------------------- ### XML Configuration for Cluster and Session in Spring Data Cassandra 2.x Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/migration-guide/migration-guide-2.2-to-3.0.adoc This XML snippet shows the configuration for cluster and session in version 2.x, including keyspace creation and startup CQL statements. ```xml CREATE TABLE … ``` -------------------------------- ### Basic Access to Person Entities (Imperative) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/repositories.adoc Demonstrates basic access to Person entities using an injected PersonRepository in an imperative Spring test. ```java @ExtendWith(SpringExtension.class) class PersonRepositoryTests { @Autowired PersonRepository repository; @Test void readsPersonTableCorrectly() { List persons = repository.findAll(); assertThat(persons.isEmpty()).isFalse(); } } ``` -------------------------------- ### Named Query Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/aot.adoc Demonstrates a simple derived query method that corresponds to a named query. ```java User findByEmailAddress(String emailAddress); ``` -------------------------------- ### Sorts Elements Correctly Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/repositories/repositories.adoc Demonstrates how to retrieve all Person entities sorted by lastname in ascending order using a Flux. ```java @Test public void sortsElementsCorrectly() { Flux people = repository.findAll(Sort.by(new Order(ASC, "lastname"))); } } ``` -------------------------------- ### Update Single Account with Bonus (Reactive) Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/template.adoc Use this snippet to reactively update a single account object by incrementing its balance. Ensure necessary imports are present. ```java import static org.springframework.data.cassandra.core.query.Criteria.where; import org.springframework.data.cassandra.core.query.Query; import org.springframework.data.cassandra.core.query.Update; … Mono wasApplied = reactiveCassandraTemplate.update(Query.query(where("id").is("foo")), Update.create().increment("balance", 50.00), Account.class); ``` -------------------------------- ### Activate Auditing with XML Configuration Source: https://github.com/spring-projects/spring-data-cassandra/blob/main/src/main/antora/modules/ROOT/pages/cassandra/auditing.adoc Configure auditing using the element in XML. Specify the auditor-aware bean using the auditor-aware-ref attribute. ```xml ```