Spring Data Cassandra Documentation

repository·main·Indexed 18 days ago

https://github.com/spring-projects/spring-data-cassandra

Spring Data for Apache Cassandra provides a Spring-based programming model for accessing Apache Cassandra NoSQL databases. It features high-level annotated POJOs, repository abstractions, and support for synchronous, reactive, and asynchronous operations. Key components include CassandraTemplate, CassandraBatchOperations for atomic batching, and EntityOperations for managing entity metadata and optimistic locking.

Tokens
35.5K
Snippets
86
Records
144
Agent score
64%

What's inside Spring Data Cassandra

  1. Overview of Spring Data for Apache Cassandra features

    main

    Spring Data for Apache Cassandra provides a comprehensive suite of tools for interacting with Apache Cassandra, ranging from low-level CQL execution to high-level object mapping and repository abstractions.

    Key features include:

    • Configuration Support: Use Java-based @Configuration classes or XML namespaces.
    • CQL Templates: CqlTemplate, AsyncCqlTemplate, and ReactiveCqlTemplate for direct CQL execution.
    • Cassandra Templates: CassandraTemplate, AsyncCassandraTemplate, and ReactiveCassandraTemplate for object mapping between CQL tables and POJOs.
    • Exception Translation: Automatic translation of Cassandra-specific errors into Spring's portable Data Access Exception Hierarchy.
    • Object Mapping: Feature-rich mapping integrated with Spring's Conversion Service, supporting annotation-based metadata.
    • Query DSLs: Java-based DSLs for queries, criteria, and updates.
    • Repository Abstraction: Automatic implementation of imperative and reactive Repository interfaces, including support for custom query methods.
  2. Overview of Reactive Cassandra Infrastructure

    main

    Spring Data for Apache Cassandra provides reactive support for interacting with Cassandra databases. Key features include:

    • Spring Configuration: Support via Java-based @Configuration classes.
    • ReactiveCqlTemplate: A helper class for common Cassandra data access operations, such as incrementing counters or performing ad-hoc CRUD. It provides callbacks to access low-level objects like com.datastax.oss.driver.api.core.CqlSession.
    • ReactiveCassandraTemplate: A high-level helper that uses ReactiveCassandraOperations to provide integrated object mapping between Cassandra tables and POJOs.
    • Exception Translation: Automatically translates Cassandra-specific errors into Spring's portable Data Access Exception Hierarchy.
    • Object Mapping: Feature-rich mapping integrated with Spring's ConversionService.
    • DSLs: Java-based Query, Criteria, and Update DSLs.
    • Repository Support: Automatic implementation of Repository interfaces, including custom finder methods.

    Spring Data for Apache Cassandra follows naming conventions consistent with the DataStax Java Driver to ensure familiarity for developers.

    For most data-oriented tasks, use ReactiveCassandraTemplate or Repository support. Use ReactiveCqlTemplate for low-level operations or counter increments.

  3. Use AbstractCassandraConfiguration for simplified setup

    main

    Extending AbstractCassandraConfiguration is the recommended way to register Spring Data for Apache Cassandra beans. It automates the wiring of CqlSession, SessionFactory, and CqlTemplate.

    Key features:

    • Automatic Bean Wiring: Handles the complex setup of necessary components.
    • Schema Generation: Supports automatic schema generation based on provided initial entities.
    • Customization: Allows providing various options like pooling, socket, and query options.
    • Astra/Cloud Support: You can customize the CqlSession creation by providing a SessionBuilderConfigurer to the configuration.

    Requirement: You must implement the getKeyspaceName() method.

    @Configuration
    public class MyCassandraConfiguration extends AbstractCassandraConfiguration {
    
        @Override
        protected String getKeyspaceName() {
            return "my_keyspace";
        }
    
        // Other overrides for pooling, socket options, etc.
    }
  4. Core concepts of CassandraTemplate and ReactiveCassandraTemplate

    main

    The CassandraTemplate (imperative/blocking) and ReactiveCassandraTemplate (reactive) are the central classes for interacting with Apache Cassandra in Spring Data. They provide high-level operations to create, update, delete, and query data while handling the mapping between domain objects and Cassandra rows.

    Key Characteristics

    • Thread-Safety: Once configured, template instances are thread-safe and reusable.
    • Interface-based usage: It is recommended to reference operations via the CassandraOperations or ReactiveCassandraOperations interfaces.
    • Mapping: Mapping is handled by a CassandraConverter (defaulting to MappingCassandraConverter), which uses metadata or naming conventions to link fields to columns.
    • Exception Translation: The templates translate native Cassandra Java driver exceptions into Spring's portable DataAccessException hierarchy.
    • Execution Models:
      • CassandraTemplate: Blocking (imperative-synchronous).
      • AsyncCassandraTemplate: Asynchronous (using CompletableFuture).
      • ReactiveCassandraTemplate: Reactive (using Project Reactor types like Mono and Flux).
  5. Choosing an approach for Cassandra database access

    main

    Spring Data for Apache Cassandra offers different levels of abstraction depending on your needs. You can mix and match these approaches within your application.

    1. Low-Level: CQL Templates

    Use CqlTemplate (classic), AsyncCqlTemplate, or ReactiveCqlTemplate when you need to perform ad-hoc CRUD operations or increment counters. This is the "lowest-level" approach and is used under the hood by the higher-level templates. It also provides callback methods to access low-level objects like com.datastax.oss.driver.api.core.CqlSession.

    2. Mid-Level: Cassandra Templates

    Use CassandraTemplate, AsyncCassandraTemplate, or ReactiveCassandraTemplate to wrap CqlTemplate. This approach provides query result-to-object mapping and allows you to use SELECT, INSERT, UPDATE, and DELETE methods instead of writing raw CQL statements.

    3. High-Level: Repository Abstraction

    Use the Repository abstraction to create declarations in your data access layer. This significantly reduces boilerplate code by automatically implementing data access logic for your entities.

  6. Understand the Spring Data repository abstraction

    main

    The Spring Data repository abstraction is designed to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores. It provides a high-level foundation for data access, though users should first understand the core Spring Data repository concepts before applying Cassandra-specific implementations.

    Before using Cassandra-specific repositories, ensure you have a sound understanding of the general Spring Data repository model, including how repository interfaces are defined and how they interact with the underlying persistence store.

  7. How reactive usage works in Cassandra (Composition vs Execution)

    main

    Reactive usage in Spring Data Cassandra is divided into two distinct phases:

    1. Composition: When you call repository methods, you are composing a reactive sequence by obtaining Publisher instances (such as Mono or Flux). At this stage, no I/O occurs.
    2. Execution: I/O is only initiated when you subscribe to the publisher. This typically happens when you pass the reactive sequence to a reactive execution infrastructure, such as Spring WebFlux or Vert.x.

    For detailed information on the underlying mechanics, refer to the Project Reactor documentation.

  8. Understanding the division of responsibilities in Spring Data Cassandra

    main

    When using Spring Data for Apache Cassandra, the responsibilities are split between the framework and the application developer.

    ActionSpringYou
    Define connection parametersX
    Open the connectionX
    Specify the CQL statementX
    Declare parameters and provide parameter valuesX
    Prepare and run the statementX
    Set up the loop to iterate through the resultsX
    Do the work for each iterationX
    Process any exceptionX
    Close the SessionX
  9. Handle vector search results with `SearchResult<T>`

    main

    When performing a vector similarity query, Spring Data returns results wrapped in SearchResults<T>.

    • SearchResults<T>: A collection of results.
    • SearchResult<T>: An individual result containing the matched domain object (T) and a Score indicating relevance.

    The Score is a numerical value (typically a float) representing how closely the matched vector aligns with the query vector. The interpretation (whether a higher score means closer or more distant) depends on the specific similarity function used.

  10. Update AsyncCqlTemplate usage for DataStax Driver 4

    main

    Because DataStax driver 4 changed the result type of asynchronous queries, you must adapt code that implements:

    • AsyncSessionCallback
    • AsyncPreparedStatementCreator

    Additionally, AsyncCqlTemplate now uses AsyncResultSetExtractor instead of ResultSetExtractor. The AsyncResultSetExtractor.extractData(...) method returns a Future instead of a scalar object, enabling fully non-blocking code in the extractor.