DATACASS-467 - Polish.
This commit is contained in:
@@ -6,7 +6,7 @@ David Webb, Matthew Adams, John Blum, Mark Paluch
|
||||
:toc-placement!:
|
||||
:spring-data-commons-docs: ../../../../spring-data-commons/src/main/asciidoc
|
||||
|
||||
(C) 2008-2016 The original author(s).
|
||||
(C) 2008-2017 The original author(s).
|
||||
|
||||
NOTE: Copies of this document may be made for your own use and for distribution to others, provided that you do not
|
||||
charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed
|
||||
@@ -16,15 +16,18 @@ toc::[]
|
||||
include::preface.adoc[]
|
||||
|
||||
:leveloffset: +1
|
||||
|
||||
include::new-features.adoc[]
|
||||
include::{spring-data-commons-docs}/dependencies.adoc[]
|
||||
include::{spring-data-commons-docs}/repositories.adoc[]
|
||||
|
||||
:leveloffset: -1
|
||||
|
||||
[[reference]]
|
||||
= Reference Documentation
|
||||
|
||||
:leveloffset: +1
|
||||
|
||||
include::reference/introduction.adoc[]
|
||||
include::reference/cassandra.adoc[]
|
||||
include::reference/converters.adoc[]
|
||||
@@ -32,6 +35,7 @@ include::reference/reactive-cassandra.adoc[]
|
||||
include::reference/cassandra-repositories.adoc[]
|
||||
include::reference/reactive-cassandra-repositories.adoc[]
|
||||
include::reference/mapping.adoc[]
|
||||
|
||||
:leveloffset: -1
|
||||
|
||||
[[appendix]]
|
||||
@@ -39,8 +43,10 @@ include::reference/mapping.adoc[]
|
||||
|
||||
:numbered!:
|
||||
:leveloffset: +1
|
||||
|
||||
include::{spring-data-commons-docs}/repository-namespace-reference.adoc[]
|
||||
include::{spring-data-commons-docs}/repository-populator-namespace-reference.adoc[]
|
||||
include::{spring-data-commons-docs}/repository-query-keywords-reference.adoc[]
|
||||
include::{spring-data-commons-docs}/repository-query-return-types-reference.adoc[]
|
||||
|
||||
:leveloffset: -1
|
||||
|
||||
@@ -1,30 +1,32 @@
|
||||
[[new-features]]
|
||||
= New & Noteworthy
|
||||
|
||||
This section summarizes changes and features for each release.
|
||||
This chapter summarizes changes and new features for each release.
|
||||
|
||||
[[new-features.2-0-0]]
|
||||
== What's new in Spring Data for Apache Cassandra 2.0
|
||||
|
||||
* Upgrade to Java 8.
|
||||
* Upgraded to Java 8.
|
||||
* <<cassandra.reactive,Reactive Apache Cassandra support>>.
|
||||
* Merge of Spring CQL and Spring Data for Apache Cassandra into a single module and package relocations from `org.springframework.cql` to `org.springframework.data.cassandra`.
|
||||
* Revised `CqlTemplate` and `AsyncCqlTemplate`/`CassandraTemplate` and `AsyncCassandraTemplate` implementations.
|
||||
* Routing capabilities via `SessionFactory` and `AbstractRoutingSessionFactory`.
|
||||
* `Update` and `Query` objects.
|
||||
* CRUD repository interface renaming: `CassandraRepository` using `MapId` is now renamed to `MapIdCassandraRepository`. `TypedIdCassandraRepository` is renamed to `CassandraRepository`.
|
||||
* Lightweight transactions via `InsertOptions` and `UpdateOptions` using the Template API.
|
||||
* Merge of Spring CQL into Spring Data Cassandra.
|
||||
* Index creation on application startup via `@Indexed` and `@SASI`.
|
||||
* New annotation for `@AllowFiltering`.
|
||||
* Merged `spring-cql` and `spring-data-cassandra` modules into a single module and re-packaged `org.springframework.cql`
|
||||
to `org.springframework.data.cassandra`.
|
||||
* Revised `CqlTemplate`, `AsyncCqlTemplate`, `CassandraTemplate` and `AsyncCassandraTemplate` implementations.
|
||||
* Added routing capabilities via `SessionFactory` and `AbstractRoutingSessionFactory`.
|
||||
* Introduced `Update` and `Query` objects.
|
||||
* Renamed CRUD _Repository_ interface: `CassandraRepository` using `MapId` is now renamed to `MapIdCassandraRepository`.
|
||||
`TypedIdCassandraRepository` is renamed to `CassandraRepository`.
|
||||
* Added lightweight transaction support via `InsertOptions` and `UpdateOptions` using the Template API.
|
||||
* Added support for Index creation on application startup via `@Indexed` and `@SASI`.
|
||||
* Introduced new annotation for `@AllowFiltering`.
|
||||
|
||||
[[new-features.1-5-0]]
|
||||
== What's new in Spring Data for Apache Cassandra 1.5
|
||||
|
||||
* Assert compatibility with Cassandra 3.0 and Cassandra Java Driver 3.0.
|
||||
* Configurable `ProtocolVersion` and `QueryOptions` on `Cluster` level.
|
||||
* Added configurable `ProtocolVersion` and `QueryOptions` on `Cluster` level.
|
||||
* Support for `Optional` as query method result and argument.
|
||||
* Declarative query methods using query derivation
|
||||
* Support for User-Defined types and mapped User-Defined types using `@UserDefinedType`.
|
||||
* The following annotations have been enabled to build own, composed annotations: `@Table`, `@UserDefinedType`, `@PrimaryKey`, `@PrimaryKeyClass`, `@PrimaryKeyColumn`, `@Column`, `@Query`, `@CassandraType`.
|
||||
* The following annotations enable building custom, composed annotations: `@Table`, `@UserDefinedType`, `@PrimaryKey`,
|
||||
`@PrimaryKeyClass`, `@PrimaryKeyColumn`, `@Column`, `@Query`, `@CassandraType`.
|
||||
|
||||
|
||||
@@ -117,3 +117,4 @@ Lastly, you can follow the Spring http://spring.io/blog[blog] or the project te
|
||||
* Release repository - https://repo.spring.io/libs-release
|
||||
* Milestone repository - https://repo.spring.io/libs-milestone
|
||||
* Snapshot repository - https://repo.spring.io/libs-snapshot
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[[cassandra.repositories]]
|
||||
= Cassandra repositories
|
||||
= Cassandra Repositories
|
||||
|
||||
[[cassandra-repo-intro]]
|
||||
== Introduction
|
||||
@@ -300,3 +300,4 @@ class RepositoryClient {
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
@@ -1,40 +1,41 @@
|
||||
[[cassandra.core]]
|
||||
= Cassandra support
|
||||
|
||||
The Cassandra support contains a wide range of features which are summarized below.
|
||||
Spring Data support for Apache Cassandra contains a wide range of features which are summarized below.
|
||||
|
||||
* Spring configuration support using Java-based `@Configuration` classes or the XML namespace.
|
||||
* `CqlTemplate` helper class that increases productivity by handling common Cassandra operations properly.
|
||||
* _Spring_ configuration support using Java-based `@Configuration` classes or the XML namespace.
|
||||
* `CqlTemplate` helper class that increases productivity by handling common Cassandra data access operations properly.
|
||||
* `CassandraTemplate` helper class providing object mapping between CQL Tables and POJOs.
|
||||
* Exception translation into Spring's portable http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#dao-exceptions[Data Access Exception Hierarchy].
|
||||
* Feature rich object mapping integrated with Spring's http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#core-convert[Conversion Service].
|
||||
* Annotation-based mapping metadata but extensible to support other metadata formats.
|
||||
* Exception translation into _Spring's_ portable http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#dao-exceptions[Data Access Exception Hierarchy].
|
||||
* Feature rich object mapping integrated with _Spring's_ http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#core-convert[Conversion Service].
|
||||
* Annotation-based mapping metadata that is extensible to support other metadata formats.
|
||||
* Java-based Query, Criteria, and Update DSLs.
|
||||
* Automatic implementation of `Repository` interfaces including support for custom finder methods.
|
||||
|
||||
For most data oriented tasks you will use the `CassandraTemplate` or the `Repository` support, which leverage the
|
||||
rich mapping functionality. `CqlTemplate` is commonly used to increment counters or perform ad-hoc CRUD
|
||||
For most data-oriented tasks you will use the `CassandraTemplate` or the `Repository` support, which leverage the
|
||||
rich object mapping functionality. `CqlTemplate` is commonly used to increment counters or perform ad-hoc CRUD
|
||||
operations. `CqlTemplate` also provides callback methods making it easy to get a hold of low-level API objects
|
||||
such as `com.datastax.driver.core.Session` allowing you to communicate directly with Cassandra. Spring Data for Apache Cassandra
|
||||
uses consistent naming conventions on objects in various APIs to those found in the DataStax Java Driver so that they
|
||||
are familiar and so you can map your existing knowledge onto the Spring APIs.
|
||||
such as `com.datastax.driver.core.Session` allowing you to communicate directly with Cassandra.
|
||||
Spring Data for Apache Cassandra uses consistent naming conventions on objects in various APIs to those found in
|
||||
the DataStax Java Driver so that they are familiar and so you can map your existing knowledge onto the _Spring_ APIs.
|
||||
|
||||
[[cassandra.getting-started]]
|
||||
== Getting Started
|
||||
|
||||
Spring Apache Cassandra support requires Apache Cassandra 2.1 or higher, Datastax Java Driver 3.0 or higher
|
||||
and Java SE 8 or higher. An easy way to bootstrap setting up a working environment is to create a Spring-based project
|
||||
in http://spring.io/tools/sts[STS].
|
||||
Spring Data for Apache Cassandra requires Apache Cassandra 2.1 or higher, Datastax Java Driver 3.0 or higher
|
||||
and Java SE 8 or higher. An easy way to quickly setup and bootstrap a working environment is to create
|
||||
a Spring-based project in http://spring.io/tools/sts[STS] or use http://start.spring.io/[Spring Initializer].
|
||||
|
||||
First you need to set up a running Apache Cassandra server. Refer to
|
||||
the http://cassandra.apache.org/doc/latest/getting_started/index.html[Apache Cassandra Quick Start guide]
|
||||
for an explanation on how to startup Apache Cassandra. Once installed starting Cassandra is typically a matter of
|
||||
First, you need to setup a running Apache Cassandra server. Refer to the
|
||||
http://cassandra.apache.org/doc/latest/getting_started/index.html[Apache Cassandra Quick Start Guide]
|
||||
for an explanation on how to startup Apache Cassandra. Once installed, starting Cassandra is typically a matter of
|
||||
executing the following command: `CASSANDRA_HOME/bin/cassandra -f`
|
||||
|
||||
To create a Spring project in STS go to File -> New -> Spring Template Project -> Simple Spring Utility Project ->
|
||||
press Yes when prompted. Then enter a project and a package name such as org.spring.cassandra.example.
|
||||
To create a Spring project in STS go to File -> New -> Spring Template Project -> Simple Spring Utility Project
|
||||
and press Yes when prompted. Then enter a project and a package name such as `org.spring.data.cassandra.example`.
|
||||
|
||||
Then, add the following dependency declaration to your _pom.xml_ `dependencies` section.
|
||||
|
||||
Then add the following to pom.xml dependencies section.
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
<dependencies>
|
||||
@@ -48,7 +49,7 @@ Then add the following to pom.xml dependencies section.
|
||||
</dependencies>
|
||||
----
|
||||
|
||||
Also change the version of Spring in the pom.xml to be
|
||||
Also, change the version of Spring in the _pom.xml_ to be
|
||||
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
@@ -56,7 +57,7 @@ Also change the version of Spring in the pom.xml to be
|
||||
----
|
||||
|
||||
If using a milestone release instead of a GA release, you will also need to add the location of the Spring Milestone
|
||||
repository for Maven to your `pom.xml` which is at the same level of your <dependencies/> element.
|
||||
repository for Maven to your _pom.xml_, which is at the same level of your `<dependencies/>` element.
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
@@ -71,9 +72,9 @@ repository for Maven to your `pom.xml` which is at the same level of your <depen
|
||||
|
||||
The repository is also http://repo.spring.io/milestone/org/springframework/data/[browseable here].
|
||||
|
||||
You can also browse the Spring repositories https://repo.spring.io/webapp/#/home[here].
|
||||
You can also browse all Spring repositories https://repo.spring.io/webapp/#/home[here].
|
||||
|
||||
Now we will create a simple Java application that stores and reads a domain object to/from Cassandra.
|
||||
Now, we will create a simple Java application that stores and reads a domain object to/from Cassandra.
|
||||
|
||||
First, create a simple domain object class to persist.
|
||||
|
||||
@@ -170,9 +171,9 @@ public class CassandraApplication {
|
||||
Even in this simple example, there are a few things to observe.
|
||||
|
||||
* You can create an instance of `CassandraTemplate` with a Cassandra `Session`, obtained from `Cluster`.
|
||||
* You must annotate your POJO as a Cassandra `@Table` and also annotate the `@PrimaryKey`. Optionally, you can
|
||||
override these mapping names to match your Cassandra database table and column names.
|
||||
* You can either use a CQL String or the DataStax `QueryBuilder` API to construct your queries.
|
||||
* You must annotate your POJO as a Cassandra `@Table` entity and also annotate the `@PrimaryKey`.
|
||||
Optionally, you can override these mapping names to match your Cassandra database table and column names.
|
||||
* You can either use raw CQL or the DataStax `QueryBuilder` API to construct your queries.
|
||||
|
||||
[[cassandra.examples-repo]]
|
||||
== Examples Repository
|
||||
@@ -183,7 +184,7 @@ can download and play around with to get a feel for how the library works.
|
||||
[[cassandra.connectors]]
|
||||
== Connecting to Cassandra with Spring
|
||||
|
||||
One of the first tasks when using Apache Cassandra and Spring is to create a `com.datastax.driver.core.Session` object
|
||||
One of the first tasks when using Apache Cassandra with Spring is to create a `com.datastax.driver.core.Session` object
|
||||
using the Spring IoC container. There are two main ways to do this, either using Java-based bean metadata or XML-based
|
||||
bean metadata. These are discussed in the following sections.
|
||||
|
||||
@@ -193,7 +194,7 @@ http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/new-in-3
|
||||
as well as the detailed documentation http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/beans.html#beans-java-instantiating-container[here].
|
||||
|
||||
[[cassandra.cassandra-java-config]]
|
||||
=== Registering a Session instance using Java based metadata
|
||||
=== Registering a Session instance using Java-based metadata
|
||||
|
||||
An example of using Java-based bean metadata to register an instance of a `com.datastax.driver.core.Session`
|
||||
is shown below.
|
||||
@@ -264,8 +265,8 @@ public class AppConfig {
|
||||
----
|
||||
====
|
||||
|
||||
Using `CassandraTemplate` with object mapping and Repository support requires a `CassandraTemplate`,
|
||||
`CassandraMappingContext`, `CassandraConverter` and enabling Repository support.
|
||||
Using `CassandraTemplate` with object mapping and _Repository_ support requires a `CassandraTemplate`,
|
||||
`CassandraMappingContext`, `CassandraConverter` and enabling _Repository_ support.
|
||||
|
||||
.Registering components to configure object mapping and repository support
|
||||
====
|
||||
@@ -371,12 +372,12 @@ cassandra.keyspace=showcase
|
||||
|
||||
We will use Spring to load these properties into the Spring context in the next two examples.
|
||||
|
||||
==== Registering a Session instance using XML based metadata
|
||||
==== Registering a Session instance using XML-based metadata
|
||||
|
||||
While you can use Spring's traditional `<beans/>` XML namespace to register an instance of
|
||||
`com.datastax.driver.core.Session` with the container, the XML can be quite verbose as it is general purpose.
|
||||
XML namespaces are a better alternative to configuring commonly used objects such as the Session instance.
|
||||
The `cql` and `cassandra` namespaces allow you to create a Session instance.
|
||||
XML namespaces are a better alternative to configuring commonly used objects such as the `Session` instance.
|
||||
The `cql` and `cassandra` namespaces allow you to create a `Session` instance.
|
||||
|
||||
To use the Cassandra namespace elements you will need to reference the Cassandra schema:
|
||||
|
||||
@@ -486,7 +487,7 @@ your base packages to scan here -->
|
||||
== Schema Management
|
||||
|
||||
Apache Cassandra is a data store that requires a schema definition prior to any data interaction.
|
||||
Spring Data for Apache Cassandra can support you with this task.
|
||||
Spring Data for Apache Cassandra can support you with schema creation.
|
||||
|
||||
=== Keyspaces and Lifecycle scripts
|
||||
|
||||
@@ -543,7 +544,8 @@ public abstract class AbstractCassandraConfiguration extends AbstractClusterConf
|
||||
----
|
||||
====
|
||||
|
||||
Startup/shutdown CQL execution follows a slightly different approach that is bound to the `Cluster` lifecycle. You can provide arbitrary CQL that is executed on `Cluster` initialization and shutdown in the `SYSTEM` keyspace.
|
||||
Startup/shutdown CQL execution follows a slightly different approach that is bound to the `Cluster` lifecycle.
|
||||
You can provide arbitrary CQL that is executed on `Cluster` initialization and shutdown in the `SYSTEM` keyspace.
|
||||
|
||||
.Specifying Startup/Shutdown scripts via XML
|
||||
====
|
||||
@@ -590,15 +592,15 @@ public class CassandraConfiguration extends AbstractCassandraConfiguration {
|
||||
NOTE: `KeyspaceSpecifications` and lifecycle CQL scripts are available with the `cql` and `cassandra` namespaces.
|
||||
|
||||
NOTE: Keyspace creation allows rapid bootstrapping without the need of external Keyspace management. This can be useful
|
||||
for certain scenarios but should be used with care. Dropping a Keyspace on application shutdown will remove the keyspace
|
||||
and all data from the tables in the keyspace.
|
||||
for certain scenarios but should be used with care. Dropping a Keyspace on application shutdown will remove the Keyspace
|
||||
and all data from the tables in the Keyspace.
|
||||
|
||||
=== Tables and User-defined types
|
||||
|
||||
Spring Data for Apache Cassandra's approaches data access with mapped entity classes that fit your data model.
|
||||
These entity classes can be used to create Cassandra table specifications and user type definitions.
|
||||
|
||||
Schema creation is tied to `Session` initialization with `SchemaAction`. Following actions are supported:
|
||||
Schema creation is tied to `Session` initialization with `SchemaAction`. The following actions are supported:
|
||||
|
||||
* `SchemaAction.NONE`: No tables/types will be created or dropped. This is the default setting.
|
||||
* `SchemaAction.CREATE`: Create tables, indexes and user-defined types from entities annotated with `@Table` and types annotated with `@UserDefinedType`. Existing tables/types will cause an error if the type is attempted to be created.
|
||||
@@ -606,7 +608,8 @@ Schema creation is tied to `Session` initialization with `SchemaAction`. Followi
|
||||
* `SchemaAction.RECREATE`: Drops and recreate existing tables and types that are known to be used. Tables and types that are not configured in the application are not dropped.
|
||||
* `SchemaAction.RECREATE_DROP_UNUSED`: Drop all tables and types and recreate only known tables and types.
|
||||
|
||||
NOTE: `SchemaAction.RECREATE`/`SchemaAction.RECREATE_DROP_UNUSED` will drop your tables and you will experience data loss. `RECREATE_DROP_UNUSED` also drops tables and types that are not known to the application.
|
||||
NOTE: `SchemaAction.RECREATE`/`SchemaAction.RECREATE_DROP_UNUSED` will drop your tables and you will lose all data.
|
||||
`RECREATE_DROP_UNUSED` also drops tables and types that are not known to the application.
|
||||
|
||||
==== Enabling Tables and User-Defined Types for Schema Management
|
||||
|
||||
@@ -642,24 +645,24 @@ public class CassandraConfiguration extends AbstractCassandraConfiguration {
|
||||
[[cassandra.cql-template]]
|
||||
== CqlTemplate
|
||||
|
||||
The `CqlTemplate` class is the central class in the CQL core package. It handles the creation and release of resources.
|
||||
The `CqlTemplate` class is the central class in the core CQL package. It handles the creation and release of resources.
|
||||
It performs the basic tasks of the core CQL workflow such as statement creation and execution, leaving application code
|
||||
to provide CQL and extract results. The `CqlTemplate` class executes CQL queries and update statements, performs
|
||||
iteration over ``ResultSet``s and extraction of returned parameter values. It also catches CQL exceptions and translates
|
||||
them to the generic, more informative, exception hierarchy defined in the `org.springframework.dao` package.
|
||||
|
||||
When you use the `CqlTemplate` for your code, you only need to implement callback interfaces, giving them a clearly
|
||||
defined contract. The `PreparedStatementCreator` callback interface creates a prepared statement given a `Connection`
|
||||
provided by this class, providing CQL and any necessary parameters. The `RowCallbackHandler` interface extracts values
|
||||
When you use the `CqlTemplate` for your code, you only need to implement callback interfaces, which have a very clearly
|
||||
defined contract. Given a `Connection` the `PreparedStatementCreator` callback interface creates a prepared statement
|
||||
with the provided CQL and any necessary parameter arguments. The `RowCallbackHandler` interface extracts values
|
||||
from each row of a `ResultSet`.
|
||||
|
||||
The `CqlTemplate` can be used within a DAO implementation through direct instantiation with a `SessionFactory` reference, or
|
||||
be configured in a Spring IoC container and given to DAOs as a bean reference. `CqlTemplate` is a foundational building
|
||||
The `CqlTemplate` can be used within a DAO implementation through direct instantiation with a `SessionFactory` reference,
|
||||
or be configured in the Spring container and given to DAOs as a bean reference. `CqlTemplate` is a foundational building
|
||||
block for <<cassandra-template,`CassandraTemplate`>>.
|
||||
|
||||
All CQL issued by this class is logged at the `DEBUG` level under the category corresponding to the fully qualified class
|
||||
name of the template instance (typically `CqlTemplate`, but it may be different if you are using a custom subclass of the
|
||||
`CqlTemplate` class).
|
||||
All CQL issued by this class is logged at the `DEBUG` level under the category corresponding to the fully-qualified class
|
||||
name of the template instance (typically `CqlTemplate`, but it may be different if you are using a custom subclass
|
||||
of the `CqlTemplate` class).
|
||||
|
||||
NOTE: `CqlTemplate` comes in different execution model flavors. The basic `CqlTemplate` uses a blocking execution model.
|
||||
You can use `AsyncCqlTemplate` for asynchronous execution and synchronization with ``ListenableFuture``s or
|
||||
@@ -668,11 +671,11 @@ You can use `AsyncCqlTemplate` for asynchronous execution and synchronization wi
|
||||
[[cassandracql-template.examples]]
|
||||
=== Examples of `CqlTemplate` class usage
|
||||
|
||||
This section provides some examples of `CqlTemplate` class usage. These examples are not an exhaustive list of all of the
|
||||
functionality exposed by the `CqlTemplate`; see the attendant javadocs for that.
|
||||
This section provides some examples of the `CqlTemplate` class in action. These examples are not an exhaustive list
|
||||
of all of the functionality exposed by the `CqlTemplate`; see the attendant Javadocs for that.
|
||||
|
||||
[[cassandra.cql-template.examples.query]]
|
||||
==== Querying (SELECT)
|
||||
==== Querying (SELECT) with `CqlTemplate`
|
||||
Here is a simple query for getting the number of rows in a relation:
|
||||
|
||||
[source,java]
|
||||
@@ -732,8 +735,9 @@ List<Actor> actors = cqlTemplate.query(
|
||||
|
||||
If the last two snippets of code actually existed in the same application, it would make sense to remove the
|
||||
duplication present in the two `RowMapper` anonymous inner classes, and extract them out into a single class
|
||||
(typically a `static` nested class) that can then be referenced by DAO methods as needed. For example, it may
|
||||
be better to write the last code snippet as follows:
|
||||
(typically a `static` nested class) that can then be referenced by DAO methods as needed.
|
||||
|
||||
For example, it may be better to write the last code snippet as follows:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -755,36 +759,36 @@ enum ActorMapper implements RowMapper<Actor> {
|
||||
----
|
||||
|
||||
[[cassandra.cql-template.examples.update]]
|
||||
==== Updating (INSERT/UPDATE/DELETE) with CqlTemplate
|
||||
==== Updating (INSERT/UPDATE/DELETE) with `CqlTemplate`
|
||||
|
||||
You use the `update(…)` method to perform insert, update and delete operations. Parameter values are usually
|
||||
provided as var args or alternatively as an object array.
|
||||
You use the `execute(…)` method to perform INSERT, UPDATE and DELETE operations. Parameter values are usually provided
|
||||
as var args or alternatively as an object array.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
cqlTemplate.execute(
|
||||
"insert into t_actor (first_name, last_name) values (?, ?)",
|
||||
"INSERT INTO t_actor (first_name, last_name) VALUES (?, ?)",
|
||||
"Leonor", "Watling");
|
||||
----
|
||||
|
||||
[source,java]
|
||||
----
|
||||
cqlTemplate.execute(
|
||||
"update t_actor set last_name = ? where id = ?",
|
||||
"UPDATE t_actor SET last_name = ? WHERE id = ?",
|
||||
"Banjo", 5276L);
|
||||
----
|
||||
|
||||
[source,java]
|
||||
----
|
||||
cqlTemplate.execute(
|
||||
"delete from actor where id = ?",
|
||||
"DELETE FROM actor WHERE id = ?",
|
||||
Long.valueOf(actorId));
|
||||
----
|
||||
|
||||
[[cassandra.cql-template.examples.other]]
|
||||
==== Other CqlTemplate operations
|
||||
==== Other `CqlTemplate` operations
|
||||
|
||||
You can use the `execute(..)` method to execute any arbitrary CQL, and as such the method is often used for DDL statements.
|
||||
You can use the `execute(..)` method to execute any arbitrary CQL. As such, the method is often used for DDL statements.
|
||||
It is heavily overloaded with variants taking callback interfaces, binding variable arrays, and so on.
|
||||
|
||||
This example shows how to create and drop a table, using different API objects, all passed to the `execute()` methods.
|
||||
@@ -803,26 +807,28 @@ cqlTemplate.execute(cql);
|
||||
include::exception-translation.adoc[]
|
||||
|
||||
[[cassandra.template]]
|
||||
== Introduction to CassandraTemplate
|
||||
== Introduction to `CassandraTemplate`
|
||||
|
||||
The `CassandraTemplate` class, located in the package `org.springframework.data.cassandra`, is the central class
|
||||
in Spring's Cassandra support providing a rich feature set to interact with the database. The template offers
|
||||
convenience operations to create, update, delete and query Cassandra and provides a mapping between your domain objects
|
||||
and Cassandra rows.
|
||||
convenience operations to create, update, delete and query Cassandra, and provides a mapping between your domain objects
|
||||
and rows in Cassandra tables.
|
||||
|
||||
NOTE: Once configured, `CassandraTemplate` is Thread-safe and can be reused across multiple instances.
|
||||
|
||||
The mapping between Cassandra rows and domain classes is done by delegating to an implementation
|
||||
The mapping between rows in Cassandra and application domain classes is done by delegating to an implementation
|
||||
of the `CassandraConverter` interface. Spring provides a default implementation, `MappingCassandraConverter`,
|
||||
but you can also write your own converter. Please refer to the section on <<mapping-chapter,Cassandra conversion>>
|
||||
for more detailed information.
|
||||
but you can also write your own custom converter. Please refer to the section on
|
||||
<<mapping-chapter,Cassandra conversion>> for more detailed information.
|
||||
|
||||
The `CassandraTemplate` class implements the interface `CassandraOperations`. In as much as possible, the methods
|
||||
on `CassandraOperations` are named after methods available with Cassandra to make the API familiar to
|
||||
existing Cassandra developers who are familiar with Cassandra. For example, you will find methods such as "select",
|
||||
"insert", "delete", and "update". The design goal was to make it as easy as possible to transition between the use
|
||||
of the base Cassandra driver and `CassandraOperations`. A major difference in between the two APIs is that
|
||||
`CassandraOperations` can be passed domain objects instead of CQL and query objects.
|
||||
The `CassandraTemplate` class implements the `CassandraOperations` interface. In as much as possible, the methods
|
||||
on `CassandraOperations` are named after methods available in Cassandra to make the API familiar to existing
|
||||
Cassandra developers who are already familiar with Cassandra.
|
||||
|
||||
For example, you will find methods such as "select", "insert", "delete", and "update". The design goal was to make it
|
||||
as easy as possible to transition between the use of the base Cassandra driver and `CassandraOperations`.
|
||||
A major difference in between the two APIs is that `CassandraOperations` can be passed domain objects instead of CQL
|
||||
and query objects.
|
||||
|
||||
NOTE: The preferred way to reference operations on a `CassandraTemplate` instance is via its interface,
|
||||
`CassandraOperations`.
|
||||
@@ -837,18 +843,20 @@ Another central feature of `CassandraTemplate` is exception translation of excep
|
||||
Java driver into Spring's portable Data Access Exception hierarchy. Refer to the section on
|
||||
<<cassandra.exception,exception translation>> for more information.
|
||||
|
||||
NOTE: `CassandraTemplate` comes in different execution model flavors. The basic `CassandraTemplate` uses a blocking execution model.
|
||||
You can use `AsyncCassandraTemplate` for asynchronous execution and synchronization with ``ListenableFuture``s or
|
||||
<<cassandra.reactive.template,`ReactiveCassandraTemplate`>> for reactive execution.
|
||||
NOTE: `CassandraTemplate` comes in different execution model flavors. The basic `CassandraTemplate` uses a
|
||||
blocking execution model. You can use `AsyncCassandraTemplate` for asynchronous execution and synchronization
|
||||
with ``ListenableFuture``s or <<cassandra.reactive.template,`ReactiveCassandraTemplate`>> for reactive execution.
|
||||
|
||||
Now let's look at examples of how to work with the `CassandraTemplate` in the context of the Spring container.
|
||||
|
||||
[[cassandra.template.instantiating]]
|
||||
=== Instantiating CassandraTemplate
|
||||
|
||||
`CassandraTemplate` should always be configured as a Spring Bean, although we show an example above where you can instantiate it directly. But for the purposes of this being a Spring module, lets assume we are using the Spring Container.
|
||||
`CassandraTemplate` should always be configured as a Spring bean, although we show an example above where
|
||||
you can instantiate it directly. But, for the purposes of this being a Spring module, lets assume we are using
|
||||
the Spring container.
|
||||
|
||||
There are 2 easy ways to get a `CassandraTemplate`, depending on how you load you Spring Application Context.
|
||||
There are 2 easy ways to get a `CassandraTemplate`, depending on how you load you Spring `ApplicationContext`.
|
||||
|
||||
[float]
|
||||
==== Autowiring
|
||||
@@ -860,13 +868,13 @@ private CassandraOperations cassandraOperations;
|
||||
----
|
||||
|
||||
Like all Spring Autowiring, this assumes there is only one bean of type `CassandraOperations` in the `ApplicationContext`.
|
||||
If you have multiple `CassandraTemplate` beans (which will be the case if you are working with multiple keyspaces
|
||||
If you have multiple `CassandraTemplate` beans (which will be the case if you are working with multiple Keyspaces
|
||||
in the same project), then use the `@Qualifier`annotation to designate which bean you want to Autowire.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@Autowired
|
||||
@Qualifier("myTemplateBeanId")
|
||||
@Qualifier("keyspaceOneTemplateBeanId")
|
||||
private CassandraOperations cassandraOperations;
|
||||
----
|
||||
|
||||
@@ -897,13 +905,17 @@ and <<mapping-conversion>> for the current type mapping matrix.
|
||||
[[cassandra.template.insert-update]]
|
||||
=== Methods for inserting and updating rows
|
||||
|
||||
There are several convenient methods on `CassandraTemplate` for saving and inserting your objects. To have more fine-grained control over the conversion process you can register Spring converters with the `MappingCassandraConverter`, for example `Converter<Row, Person>`.
|
||||
There are several convenient methods on `CassandraTemplate` for saving and inserting your objects. To have more
|
||||
fine-grained control over the conversion process you can register Spring `Converters` with the `MappingCassandraConverter`.
|
||||
For example, `Converter<Row, Person>`.
|
||||
|
||||
NOTE: The difference between insert and update operations is that an `INSERT` operation will not insert `null` values.
|
||||
|
||||
The simple case of using the insert operation is to save a POJO. In this case the table name will be determined by name (not fully qualified) of the class. The table to store the object can be overridden using mapping metadata.
|
||||
The simple case of using the insert operation is to save a POJO. In this case, the table name will be determined
|
||||
by the simple name of the class (not fully-qualified). The table to store the object can be overridden
|
||||
using mapping metadata.
|
||||
|
||||
When inserting or updating, if the Id property is must be set. There are no means to generate an Id by Apache Cassandra.
|
||||
When inserting or updating, the `id` property must be set. There is no means to generate an ID with Apache Cassandra.
|
||||
|
||||
Here is a basic example of using the save operation and retrieving its contents.
|
||||
|
||||
@@ -915,42 +927,52 @@ import static org.springframework.data.cassandra.core.query.Criteria.where;
|
||||
import static org.springframework.data.cassandra.core.query.Query.query;
|
||||
…
|
||||
|
||||
Person p = new Person("Bob", 33);
|
||||
cassandraTemplate.insert(p);
|
||||
Person bob = new Person("Bob", 33);
|
||||
cassandraTemplate.insert(bob);
|
||||
|
||||
Person qp = cassandraTemplate.selectOneById(query(where("age").is(33)), Person.class);
|
||||
Person queriedBob = cassandraTemplate.selectOneById(query(where("age").is(33)), Person.class);
|
||||
----
|
||||
====
|
||||
|
||||
The insert/save operations available to you are listed below.
|
||||
|
||||
* `void` *insert* `(Object objectToSave)` Insert the object in an Apache Cassandra table.
|
||||
* `WriteResult` *insert* `(Object objectToSave, InsertOptions options)` Insert the object in an Apache Cassandra table applying `InsertOptions`.
|
||||
* `WriteResult` *insert* `(Object objectToSave, InsertOptions options)` Insert the object in an Apache Cassandra table
|
||||
applying `InsertOptions`.
|
||||
|
||||
A similar set of update operations is listed below
|
||||
|
||||
* `void` *update* `(Object objectToSave)` Update the object in an Apache Cassandra table.
|
||||
* `WriteResult` *update* `(Object objectToSave, UpdateOptions options)` Update the object in an Apache Cassandra table applying `UpdateOptions`.
|
||||
* `WriteResult` *update* `(Object objectToSave, UpdateOptions options)` Update the object in an Apache Cassandra table
|
||||
applying `UpdateOptions`.
|
||||
|
||||
Then, there is always the old fashioned way. You can write your own CQL statements. You can configure with `InsertOptions` and `UpdateOptions`
|
||||
additional options such as TTL, consistency level and lightweight transactions.
|
||||
Then, there is always the old fashioned way; you can write your own CQL statements.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
String cql = "insert into person (age, name) values (39, 'Bob')";
|
||||
String cql = "INSERT INTO person (age, name) VALUES (39, 'Bob')";
|
||||
|
||||
cassandraTemplate().getCqlOperations().execute(cql);
|
||||
----
|
||||
|
||||
You can also configure additional options such as TTL, consistency level and lightweight transactions
|
||||
using `InsertOptions` and `UpdateOptions`.
|
||||
|
||||
[[cassandra.template.insert-update.table]]
|
||||
==== Which table will my rows be inserted into?
|
||||
|
||||
There are two ways to manage the collection name that is used for operating on the tables. The default table name that is used is the class name changed to start with a lower-case letter. So a `com.test.Person` class would be stored in the "person" table. You can customize this by providing a different collection name using the `@Table` annotation.
|
||||
There are two ways to manage the collection name that is used for operating on the tables. The default table name
|
||||
that is used is the simple class name changed to start with a lower-case letter. So, an instance of
|
||||
the `com.example.Person` class would be stored in the "person" table.
|
||||
|
||||
You can customize this by providing a different collection name using the `@Table` annotation.
|
||||
|
||||
[[cassandra.template.batch]]
|
||||
==== Inserting, updating and deleting individual objects in a batch
|
||||
|
||||
The Cassandra protocol supports inserting a collection of rows in one operation using a batch. The methods in the `CassandraTemplate` interface that support this functionality are listed below
|
||||
The Cassandra protocol supports inserting a collection of rows in one operation using a batch.
|
||||
|
||||
The methods in the `CassandraTemplate` interface supporting this functionality are listed below.
|
||||
|
||||
* *batchOps* Creates a new `CassandraBatchOperations` to populate the batch
|
||||
|
||||
@@ -965,7 +987,10 @@ The Cassandra protocol supports inserting a collection of rows in one operation
|
||||
[[cassandra.template.update]]
|
||||
=== Updating rows in a table
|
||||
|
||||
For updates we can select to update a number of rows. Here is an example of an update a single account object where we are adding a one-time $50.00 bonus to the balance using the `+` assignment.
|
||||
For updates, we can select to update a number of rows.
|
||||
|
||||
Here is an example of updating a single account object where we are adding a one-time $50.00 bonus to the balance
|
||||
using the `+` assignment.
|
||||
|
||||
.Updating rows using `CasandraTemplate`
|
||||
====
|
||||
@@ -982,21 +1007,25 @@ boolean applied = cassandraTemplate.update(Query.query(where("id").is("foo")),
|
||||
----
|
||||
====
|
||||
|
||||
In addition to the `Query` discussed above we provide the update definition using an `Update` object. The `Update` class has methods that match the update assignments available for Apache Cassandra.
|
||||
In addition to the `Query` discussed above, we provide the update definition using an `Update` object.
|
||||
The `Update` class has methods that match the update assignments available for Apache Cassandra.
|
||||
|
||||
As you can see most methods return the `Update` object to provide a fluent style for the API.
|
||||
As you can see most methods return the `Update` object to provide a fluent API for code styling purposes.
|
||||
|
||||
[[cassandra.template.update.methods]]
|
||||
==== Methods for executing updates for rows
|
||||
|
||||
* `boolean` *update* `(Query query, Update update, Class<?> entityClass)` Update a selection of objects in the Apache Cassandra table.
|
||||
* `boolean` *update* `(Query query, Update update, Class<?> entityClass)` Update a selection of objects in
|
||||
the Apache Cassandra table.
|
||||
|
||||
[[cassandra.template.update.update]]
|
||||
==== Methods for the Update class
|
||||
|
||||
The Update class can be used with a little 'syntax sugar' as its methods are meant to be chained together and you can kick-start the creation of a new Update instance via the static method `public static Update update(String key, Object value)` and using static imports.
|
||||
The `Update` class can be used with a little 'syntax sugar' as its methods are meant to be chained together
|
||||
and you can kick-start the creation of a new `Update` instance via the static method
|
||||
`public static Update update(String key, Object value)` and using static imports.
|
||||
|
||||
Here is a listing of methods on the Update class
|
||||
Here is a listing of methods on the `Update` class.
|
||||
|
||||
* `AddToBuilder` *addTo* `(String columnName)` `AddToBuilder` entry-point:
|
||||
** Update `prepend(Object value)` Prepend a collection value to the existing collection using the `+` update assignment.
|
||||
@@ -1041,13 +1070,21 @@ You can use several overloaded methods to remove an object from the database.
|
||||
[[cassandra.template.query]]
|
||||
== Querying Rows
|
||||
|
||||
You can express your queries using the `Query` and `Criteria` classes which have method names that reflect the native Cassandra predicates operator names such as `lt`, `lte`, `is`, and others. The `Query` and `Criteria` classes follow a fluent API style so that you can easily chain together multiple method criteria and queries while having easy to understand the code. Static imports in Java are used to help creating `Query` and `Criteria` instances so as to improve readability.
|
||||
You can express your queries using the `Query` and `Criteria` classes, which have method names that reflect
|
||||
the native Cassandra predicate operator names such as `lt`, `lte`, `is`, and others.
|
||||
|
||||
The `Query` and `Criteria` classes follow a fluent API style so you can easily chain together multiple method criteria
|
||||
and queries while having easy to understand the code. Static imports are used in Java when creating `Query`
|
||||
and `Criteria` instances to improve readability.
|
||||
|
||||
|
||||
[[cassandra.template.query.table]]
|
||||
=== Querying rows in a table
|
||||
|
||||
We saw how to retrieve a single object using the `selectOneById` method on `CassandraTemplate` in previous sections which return a single domain object. We can also query for a collection of rows to be returned as a list of domain objects. Assuming that we have a number of Person objects with name and age stored as rows in a table and that each person has an account balance. We can now run a query using the following code.
|
||||
We saw how to retrieve a single object using the `selectOneById` method on `CassandraTemplate` in previous sections,
|
||||
which return a single domain object. We can also query for a collection of rows to be returned as a
|
||||
list of domain objects. Assuming we have a number of Person objects with name and age stored as rows in a table
|
||||
and that each person has an account balance, we can now run a query using the following code.
|
||||
|
||||
.Querying for rows using `CassandraTemplate`
|
||||
====
|
||||
@@ -1063,9 +1100,13 @@ List<Person> result = cassandraTemplate.select(query(where("age").is(50))
|
||||
----
|
||||
====
|
||||
|
||||
`select`, `selectOneById` and `stream` methods take a `Query` object as a parameter. This object defines the criteria and options used to perform the query. The criteria is specified using a `Criteria` object that has a static factory method named `where` used to instantiate a new `Criteria` object. We recommend using a static import for `org.springframework.data.cassandra.core.query.Criteria.where` and `Query.query` to make the query more readable.
|
||||
`select`, `selectOneById` and `stream` methods take a `Query` object as a parameter. This object defines the criteria
|
||||
and options used to perform the query. The criteria is specified using a `Criteria` object that has
|
||||
a static factory method named `where` used to instantiate a new `Criteria` object. We recommend using a static import
|
||||
for `org.springframework.data.cassandra.core.query.Criteria.where` and `Query.query` to make the query more readable.
|
||||
|
||||
This query should return a list of `Person` objects that meet the specified criteria. The `Criteria` class has the following methods that correspond to the operators provided in Apache Cassandra.
|
||||
This query should return a list of `Person` objects that meet the specified criteria. The `Criteria` class has
|
||||
the following methods that correspond to the operators provided in Apache Cassandra.
|
||||
|
||||
[[cassandra.template.query.criteria]]
|
||||
==== Methods for the Criteria class
|
||||
@@ -1111,3 +1152,4 @@ The query methods need to specify the target type T that will be returned.
|
||||
* `List<T>` *select* `(String cql, Class<T> entityClass)` Ad-hoc query for a list of objects of type T from the table providing a CQL statement.
|
||||
* `T` *selectOneById* `(String cql, Class<T> entityClass)` Ad-hoc query for a single object of type T from the table providing a CQL statement.
|
||||
* `Stream<T>` *stream* `(String cql, Class<T> entityClass)` Ad-hoc query for a stream of objects of type T from the table providing a CQL statement.
|
||||
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
[[cassandra.custom-converters]]
|
||||
== Overriding default mapping with custom converters
|
||||
|
||||
In order to have more fine grained control over the mapping process you can register Spring converters with
|
||||
the `CassandraConverter` implementations such as the `MappingCassandraConverter`.
|
||||
In order to have more fine-grained control over the mapping process, you can register Spring `Converters` with
|
||||
`CassandraConverter` implementations, such as the `MappingCassandraConverter`.
|
||||
|
||||
The `MappingCassandraConverter` checks to see if there are any Spring converters that can handle a specific class
|
||||
before attempting to map the object itself. To 'hijack' the normal mapping strategies of the `MappingCassandraConverter`,
|
||||
perhaps for increased performance or other custom mapping needs, you first need to create an implementation of
|
||||
the Spring `Converter` interface and then register it with the `MappingCassandraConverter`.
|
||||
The `MappingCassandraConverter` first checks to see whether there are any Spring `Converters` that can handle
|
||||
a specific class before attempting to map the object itself. To 'hijack' the normal mapping strategies
|
||||
of the `MappingCassandraConverter`, perhaps for increased performance or other custom mapping needs, you first
|
||||
need to create an implementation of the Spring `Converter` interface and then register it with
|
||||
the `MappingCassandraConverter`.
|
||||
|
||||
NOTE: For more information on the Spring type conversion service see the reference docs
|
||||
NOTE: For more information on Spring's type conversion service, see the reference docs
|
||||
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#core-convert[here].
|
||||
|
||||
[[cassandra.custom-converters.writer]]
|
||||
=== Saving using a registered Spring Converter
|
||||
|
||||
An example implementation of the `Converter` that converts a `Person` object to a `java.lang.String`
|
||||
An example implementation of a `Converter` that converts a `Person` object to a `java.lang.String`
|
||||
using Jackson 2 is shown below:
|
||||
|
||||
[source,java]
|
||||
@@ -41,7 +42,7 @@ static class PersonWriteConverter implements Converter<Person, String> {
|
||||
[[cassandra.custom-converters.reader]]
|
||||
=== Reading using a Spring Converter
|
||||
|
||||
An example implementation of the `Converter` that converts a `java.lang.String` into a `Person` object
|
||||
An example implementation of a `Converter` that converts a `java.lang.String` into a `Person` object
|
||||
using Jackson 2 is shown below:
|
||||
|
||||
[source,java]
|
||||
@@ -71,9 +72,9 @@ static class PersonReadConverter implements Converter<String, Person> {
|
||||
[[cassandra.custom-converters.java]]
|
||||
=== Registering Spring Converters with the CassandraConverter
|
||||
|
||||
The Spring Data for Apache Cassandra Java Config provides a convenient way to register Spring `Converter`s with
|
||||
the `MappingCassandraConverter`. The configuration snippet below shows how to manually register converters as well as
|
||||
configuring the `CustomConversions`.
|
||||
Spring Data for Apache Cassandra Java Config provides a convenient way to register Spring `Converter`s
|
||||
with the `MappingCassandraConverter`. The configuration snippet below shows how to manually register converters
|
||||
as well as configure `CustomConversions`.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -84,6 +85,7 @@ public static class Config extends AbstractCassandraConfiguration {
|
||||
public CustomConversions customConversions() {
|
||||
|
||||
List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
|
||||
|
||||
converters.add(new PersonReadConverter());
|
||||
converters.add(new PersonWriteConverter());
|
||||
|
||||
@@ -97,9 +99,11 @@ public static class Config extends AbstractCassandraConfiguration {
|
||||
[[cassandra.converter-disambiguation]]
|
||||
=== Converter disambiguation
|
||||
|
||||
Generally, we inspect the `Converter` implementations for both source and target types they convert from and to.
|
||||
Generally, we inspect the `Converter` implementations for both the source and target types they convert from and to.
|
||||
Depending on whether one of those is a type Cassandra can handle natively, Spring Data will register the `Converter`
|
||||
instance as a reading or writing one. Have a look at the following samples:
|
||||
instance as a reading or writing one.
|
||||
|
||||
Have a look at the following samples:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -110,11 +114,12 @@ class MyConverter implements Converter<Person, String> { … }
|
||||
class MyConverter implements Converter<String, Person> { … }
|
||||
----
|
||||
|
||||
In case you write a `Converter` whose source and target type are native Cassandra types there's no way for Spring Data
|
||||
to determine whether we should consider it as reading or writing `Converter`. Registering the `Converter` instance
|
||||
as both might lead to unwanted results.
|
||||
In case you implement a `Converter` whose source and target types are native Cassandra types, there's no way
|
||||
for Spring Data to determine whether we should consider it as a reading or writing `Converter`.
|
||||
Registering the `Converter` instance as both might lead to unwanted results.
|
||||
|
||||
E.g. a `Converter<String, Long>` is ambiguous although it probably does not make sense to try to convert all `String`
|
||||
instances into `Long` instances when writing. To be generally able to force the infrastructure to register a `Converter`
|
||||
instances into `Long` instances when writing. To generally be able to force the infrastructure to register a `Converter`
|
||||
for one way only we provide `@ReadingConverter` as well as `@WritingConverter` to be used as the appropriate
|
||||
`Converter` implementation.
|
||||
`Converter` implementation.
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
== Exception Translation
|
||||
|
||||
The Spring Framework provides exception translation for a wide variety of database and mapping technologies.
|
||||
This has traditionally been for JDBC and JPA. The Spring support for Apache Cassandra extends this feature
|
||||
to Apache Cassandra by providing an implementation of the `org.springframework.dao.support.PersistenceExceptionTranslator`
|
||||
interface.
|
||||
This has traditionally been for JDBC and JPA. Spring Data for Apache Cassandra extends this feature to Apache Cassandra
|
||||
by providing an implementation of the `org.springframework.dao.support.PersistenceExceptionTranslator` interface.
|
||||
|
||||
The motivation behind mapping to Spring's http://docs.spring.io/spring/docs/current/spring-framework-reference/html/dao.html#dao-exceptions[consistent data access exception hierarchy]
|
||||
is that you are then able to write portable and descriptive exception handling code without resorting to coding
|
||||
against Cassandra Exceptions. All of Spring's data access exceptions are inherited from the root, `DataAccessException`
|
||||
class so you can be sure that you will be able to catch all database related exception within a single try-catch block.
|
||||
is that you are then able to write portable and descriptive exception handling code without resorting to coding against
|
||||
and handling specific Cassandra Exceptions. All of Spring's data access exceptions are inherited from the root,
|
||||
`DataAccessException` class so you can be sure that you will be able to catch all database related exceptions
|
||||
within a single try-catch block.
|
||||
|
||||
|
||||
@@ -6,16 +6,16 @@ This part of the reference documentation explains the core functionality offered
|
||||
|
||||
<<cassandra.reactive>> explains reactive Cassandra specifics.
|
||||
|
||||
<<cassandra.repositories>> introduce repository support for Cassandra.
|
||||
<<cassandra.repositories>> introduces _Repository_ support for Cassandra.
|
||||
|
||||
[[cassandra.modules]]
|
||||
== Spring CQL and Spring Data for Apache Cassandra modules
|
||||
|
||||
Spring Data for Apache Cassandra allows interaction on CQL and entity-level.
|
||||
Spring Data for Apache Cassandra allows interaction on both the CQL as well as the entity-level.
|
||||
|
||||
The value-add provided by the Spring Data Cassandra abstraction is perhaps best shown by the sequence of actions
|
||||
outlined in the table below. The table shows what actions Spring will take care of and which actions are
|
||||
the responsibility of you, the application developer.
|
||||
The value-add provided by the Spring Data for Apache Cassandra abstraction is perhaps best shown by
|
||||
the sequence of actions outlined in the table below. The table shows what actions Spring will take care of
|
||||
and which actions are the responsibility of you, the application developer.
|
||||
|
||||
[[cassandra.modules.who-does-what]]
|
||||
.Spring Data for Apache Cassandra (CQL Core)- who does what?
|
||||
@@ -59,22 +59,26 @@ the responsibility of you, the application developer.
|
||||
|
|
||||
|===
|
||||
|
||||
The CQL core takes care of all the low-level details that can make Cassandra and CQL such a tedious API to develop with.
|
||||
Using mapped entity objects allows schema generation, object mapping and Repository support.
|
||||
The core CQL support takes care of all the low-level details that can make Cassandra and CQL such a tedious API
|
||||
to develop with. Using mapped entity objects allows schema generation, object mapping and _Repository_ support.
|
||||
|
||||
[[cassandra.choose-style]]
|
||||
=== Choosing an approach for Cassandra database access
|
||||
|
||||
You can choose among several approaches to form the basis for your Cassandra database access. Spring's support
|
||||
You can choose among several approaches to use as a basis for your Cassandra database access. Spring's support
|
||||
for Apache Cassandra comes in different flavors. Once you start using one of these approaches, you can still mix
|
||||
and match to include a feature from a different approach.
|
||||
|
||||
* <<cassandra.cql-template,__CqlTemplate__>> and <<cassandra.reactive.cql-template,__ReactiveCqlTemplate__>> are the classic Spring CQL approach and the most popular. This is the "lowest level" approach and components like `CassandraTemplate` use `CqlTemplate` under the covers.
|
||||
* <<cassandra.template,__CassandraTemplate__>> wraps a `CqlTemplate` to provide query result to object mapping and the use of `SELECT`, `INSERT`,
|
||||
`UPDATE` and `DELETE` methods instead of writing CQL statements. This approach provides better documentation and ease of use.
|
||||
* <<cassandra.reactive.template,__ReactiveCassandraTemplate__>> wraps a `ReactiveCqlTemplate` to provide query result to object mapping and the use of `SELECT`, `INSERT`,
|
||||
`UPDATE` and `DELETE` methods instead of writing CQL statements. This approach provides better documentation and ease of use.
|
||||
* __Repository Abstraction__ allows you to create Repository declarations in your data access layer. The goal of
|
||||
Spring Data's Repository abstraction is to significantly reduce the amount of boilerplate code required to implement
|
||||
* <<cassandra.cql-template,__CqlTemplate__>> and <<cassandra.reactive.cql-template,__ReactiveCqlTemplate__>> are the
|
||||
classic Spring CQL approach and the most popular. This is the "lowest level" approach and components like `CassandraTemplate`
|
||||
use `CqlTemplate` under-the-hood.
|
||||
* <<cassandra.template,__CassandraTemplate__>> wraps a `CqlTemplate` to provide query result to object mapping
|
||||
and the use of `SELECT`, `INSERT`, `UPDATE` and `DELETE` methods instead of writing CQL statements. This approach
|
||||
provides better documentation and ease of use.
|
||||
* <<cassandra.reactive.template,__ReactiveCassandraTemplate__>> wraps a `ReactiveCqlTemplate` to provide query result
|
||||
to object mapping and the use of `SELECT`, `INSERT`, `UPDATE` and `DELETE` methods instead of writing CQL statements.
|
||||
This approach provides better documentation and ease of use.
|
||||
* __Repository Abstraction__ allows you to create _Repository_ declarations in your data access layer. The goal of
|
||||
Spring Data's _Repository_ abstraction is to significantly reduce the amount of boilerplate code required to implement
|
||||
data access layers for various persistence stores.
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
[[mapping.chapter]]
|
||||
= Mapping
|
||||
|
||||
Rich mapping support is provided by the `MappingCassandraConverter` . `MappingCassandraConverter` has a rich
|
||||
metadata model that provides a complete feature set of functionality to map domain objects to CQL Tables.
|
||||
Rich object mapping support is provided by the `MappingCassandraConverter`. `MappingCassandraConverter` has a
|
||||
rich metadata model that provides a complete feature set of functionality to map domain objects to CQL tables.
|
||||
|
||||
The mapping metadata model is populated using annotations on your domain objects. However, the infrastructure
|
||||
is not limited to using annotations as the only source of metadata. The `MappingCassandraConverter` also allows you
|
||||
to map domain objects to tables without providing any additional metadata, by following a set of conventions.
|
||||
@@ -10,27 +11,15 @@ to map domain objects to tables without providing any additional metadata, by fo
|
||||
In this section we will describe the features of the `MappingCassandraConverter`, how to use conventions for
|
||||
mapping domain objects to tables and how to override those conventions with annotation-based mapping metadata.
|
||||
|
||||
[[mapping-conventions]]
|
||||
== Convention based Mapping
|
||||
|
||||
`MappingCassandraConverter` uses a few conventions for mapping domain objects to CQL Tables when no additional
|
||||
mapping metadata is provided. The conventions are:
|
||||
|
||||
* The short Java class name is mapped to the table name in the following manner. The class `com.bigbank.SavingsAccount`
|
||||
maps to `savingsaccount` table name.
|
||||
* The converter will use any registered Spring Converters to override the default mapping of object properties to
|
||||
tables fields.
|
||||
* The properties of an object are used to convert to and from properties in the table.
|
||||
|
||||
|
||||
[[mapping-conversion]]
|
||||
== Data mapping and type conversion
|
||||
== Data Mapping and Type Conversion
|
||||
|
||||
This section explains how types are mapped to an Apache Cassandra representation and vice versa.
|
||||
|
||||
Spring Data for Apache Cassandra supports several types that are provided by Apache Cassandra. In addition to
|
||||
these types, Spring Data for Apache Cassandra provides a set of built-in converters to map additional types.
|
||||
You can provide your own converters to adjust type conversion, see <<cassandra.mapping.explicit-converters>>
|
||||
You can provide your own custom converters to adjust type conversion, see <<cassandra.mapping.explicit-converters>>
|
||||
for further details.
|
||||
|
||||
[cols="3,2", options="header"]
|
||||
@@ -84,7 +73,7 @@ for further details.
|
||||
| `java.util.UUID`
|
||||
| `timeuuid`
|
||||
|
||||
| `UDTValue`, mapped User-Defined types
|
||||
| `UDTValue`, mapped User-Defined Types
|
||||
| user type
|
||||
|
||||
| `java.util.Map<K, V>`
|
||||
@@ -116,7 +105,7 @@ Each supported type maps to a default
|
||||
https://docs.datastax.com/en/cql/3.3/cql/cql_reference/cql_data_types_c.html[Cassandra data type].
|
||||
Java types can be mapped to other Cassandra types by using `@CassandraType`.
|
||||
|
||||
.Enum Mapping to Numeric types
|
||||
.Enum Mapping to Numeric Types
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@@ -134,9 +123,23 @@ public enum Condition {
|
||||
----
|
||||
====
|
||||
|
||||
NOTE: `Enum` mapping using ordinal values requires at least Spring 4.3.0. Using earlier Spring versions require
|
||||
NOTE: `Enum` mapping using ordinal values requires at least Spring 4.3.0. Using earlier Spring versions requires
|
||||
<<mapping-explicit-converters,custom converters>> for each `Enum` type.
|
||||
|
||||
|
||||
[[mapping-conventions]]
|
||||
== Convention-based Mapping
|
||||
|
||||
`MappingCassandraConverter` uses a few conventions for mapping domain objects to CQL tables when no additional
|
||||
mapping metadata is provided. The conventions are:
|
||||
|
||||
* The simple (short) Java class name is mapped to the table name in the following manner.
|
||||
The class `com.bigbank.SavingsAccount` maps to a table named, "`savingsaccount`".
|
||||
* The converter will use any registered Spring `Converter`s to override the default mapping of object properties to
|
||||
tables fields.
|
||||
* The properties of an object are used to convert to and from properties in the table.
|
||||
|
||||
|
||||
[[mapping-configuration]]
|
||||
=== Mapping Configuration
|
||||
|
||||
@@ -144,10 +147,9 @@ Unless explicitly configured, an instance of `MappingCassandraConverter` is crea
|
||||
a `CassandraTemplate`. You can create your own instance of the `MappingCassandraConverter` so as to tell it
|
||||
where to scan the classpath at startup for your domain classes in order to extract metadata and construct indexes.
|
||||
|
||||
Also, by creating your own instance you can register Spring Converters to use for mapping specific classes
|
||||
Also, by creating your own instance you can register Spring `Converter`s to use for mapping specific classes
|
||||
to and from the database.
|
||||
|
||||
|
||||
.@Configuration class to configure Cassandra mapping support
|
||||
====
|
||||
[source,java]
|
||||
@@ -166,6 +168,7 @@ public static class Config extends AbstractCassandraConfiguration {
|
||||
public CustomConversions customConversions() {
|
||||
|
||||
List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
|
||||
|
||||
converters.add(new PersonReadConverter());
|
||||
converters.add(new PersonWriteConverter());
|
||||
|
||||
@@ -182,24 +185,24 @@ public static class Config extends AbstractCassandraConfiguration {
|
||||
----
|
||||
====
|
||||
|
||||
`AbstractCassandraConfiguration` requires you to implement methods that define a keyspace.
|
||||
`AbstractCassandraConfiguration` requires you to implement methods that define a Keyspace.
|
||||
`AbstractCassandraConfiguration` also has a method you can override named `getEntityBasePackages(…)`
|
||||
which tells the `Converter` where to scan for classes annotated with the `@Table` annotation.
|
||||
which tells the converter where to scan for classes annotated with the `@Table` annotation.
|
||||
|
||||
You can add additional converters to the `Converter` by overriding the method `customConversions`.
|
||||
You can add additional converters to the `MappingCassandraConverter` by overriding the method `customConversions`.
|
||||
|
||||
NOTE: `AbstractCassandraConfiguration` will create a `CassandraTemplate` instance and register it with the container
|
||||
under the name `cassandraTemplate`.
|
||||
|
||||
|
||||
[[mapping.usage]]
|
||||
== Metadata based Mapping
|
||||
== Metadata-based Mapping
|
||||
|
||||
To take full advantage of the object mapping functionality inside the Spring Data for Apache Cassandra support,
|
||||
you should annotate your mapped objects with the `@Table` annotation. It allows the classpath scanner to find
|
||||
you should annotate your mapped domain objects with the `@Table` annotation. It allows the classpath scanner to find
|
||||
and pre-process your domain objects to extract the necessary metadata. Only annotated entities will be used
|
||||
to perform schema actions. In the worst case, a `SchemaAction.RECREATE_DROP_UNUSED` will drop your tables
|
||||
and you will experience data loss.
|
||||
and you will lose your data.
|
||||
|
||||
.Example domain object
|
||||
====
|
||||
@@ -226,11 +229,12 @@ public class Person {
|
||||
IMPORTANT: The `@Id` annotation tells the mapper which property you want to use for the Cassandra primary key.
|
||||
Composite primary keys can require a slightly different data model.
|
||||
|
||||
|
||||
[[cassandra-template.id-handling]]
|
||||
=== Working with Primary Keys
|
||||
|
||||
Cassandra requires at least one partition key field for a CQL Table. A table can declare additionally one or more
|
||||
clustering key fields. When your CQL Table has a composite primary key, you must create a `@PrimaryKeyClass` to define
|
||||
Cassandra requires at least one partition key field for a CQL table. A table can additionally declare one or more
|
||||
clustering key fields. When your CQL table has a composite primary key, you must create a `@PrimaryKeyClass` to define
|
||||
the structure of the composite primary key. In this context, composite primary key means one or more partition columns
|
||||
optionally combined with one or more clustering columns.
|
||||
|
||||
@@ -268,7 +272,7 @@ public class LoginEvent {
|
||||
private String firstname;
|
||||
private String lastname;
|
||||
|
||||
// getters and setters omitted for brevity
|
||||
// getters and setters omitted
|
||||
|
||||
}
|
||||
----
|
||||
@@ -276,7 +280,7 @@ public class LoginEvent {
|
||||
|
||||
==== Composite Key
|
||||
|
||||
Composite primary keys (or compound keys) consist of more than one primary key fields. That said, a composite primary key
|
||||
Composite primary keys (or compound keys) consist of more than one primary key field. That said, a composite primary key
|
||||
can consist of multiple partition keys, a partition key and a clustering key, or a multitude of primary key fields.
|
||||
|
||||
Composite keys can be represented in two ways with Spring Data for Apache Cassandra:
|
||||
@@ -286,7 +290,7 @@ Composite keys can be represented in two ways with Spring Data for Apache Cassan
|
||||
|
||||
The simplest form of a composite key is a key with one partition key and one clustering key.
|
||||
|
||||
Here is an example of a CQL Table, and the corresponding POJOs that represent the table and it's composite key.
|
||||
Here is an example of a CQL table and the corresponding POJOs that represent the table and it's composite key.
|
||||
|
||||
.CQL Table with a Composite Primary Key
|
||||
====
|
||||
@@ -328,7 +332,7 @@ public class LoginEvent {
|
||||
@Column("ip_address)
|
||||
private String ipAddress;
|
||||
|
||||
// getters and setters omitted for brevity
|
||||
// getters and setters omitted
|
||||
}
|
||||
----
|
||||
====
|
||||
@@ -338,7 +342,7 @@ public class LoginEvent {
|
||||
A primary key class is a composite primary key class that is mapped to multiple fields or properties of the entity.
|
||||
It's annotated with `@PrimaryKeyClass` and defines `equals` and `hashCode` methods. The semantics of value equality
|
||||
for these methods should be consistent with the database equality for the database types to which the key is mapped.
|
||||
Primary key classes can be used with Repositories (as the Id type) and to represent an entities' identity
|
||||
Primary key classes can be used with _Repositories_ (as the Id type) and to represent an entities' identity
|
||||
in a single complex object.
|
||||
|
||||
.Composite Primary Key Class
|
||||
@@ -357,7 +361,7 @@ public class LoginEventKey implements Serializable {
|
||||
@PrimaryKeyColumn(name = "event_time", ordinal = 2, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING)
|
||||
private Date eventTime;
|
||||
|
||||
// other methods omitted for brevity
|
||||
// other methods omitted
|
||||
}
|
||||
----
|
||||
====
|
||||
@@ -375,18 +379,19 @@ public class LoginEvent {
|
||||
@Column("ip_address)
|
||||
private String ipAddress;
|
||||
|
||||
// getters and setters omitted for brevity
|
||||
// getters and setters omitted
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
NOTE: `PrimaryKeyClass` must implement `Serializable` and should provide implementations of `hashCode()` and `equals()`.
|
||||
NOTE: `PrimaryKeyClass` must implement `Serializable` and should provide implementations of `equals()` and `hashCode()`.
|
||||
|
||||
|
||||
[[mapping.usage-annotations]]
|
||||
=== Mapping annotation overview
|
||||
|
||||
The `MappingCassandraConverter` can use metadata to drive the mapping of objects to rows. An overview of the annotations
|
||||
is provided below:
|
||||
The `MappingCassandraConverter` can use metadata to drive the mapping of objects to rows in a Cassandra table.
|
||||
An overview of the annotations is provided below:
|
||||
|
||||
* `@Id` - applied at the field or property level to mark the property used for identity purpose.
|
||||
* `@Table` - applied at the class level to indicate this class is a candidate for mapping to the database.
|
||||
@@ -394,21 +399,22 @@ You can specify the name of the table where the object will be stored.
|
||||
* `@PrimaryKey` - Similar to `@Id` but allows you to specify the column name.
|
||||
* `@PrimaryKeyColumn` - Cassandra-specific annotation for primary key columns that allows you to specify
|
||||
primary key column attributes such as for clustered/partitioned. Can be used on single and multiple attributes
|
||||
to indicate either a single or a compound primary key.
|
||||
* `@PrimaryKeyClass` - applied at the class level to indicate this class is a compound primary key class. Requires to
|
||||
be referenced with `@PrimaryKey`.
|
||||
to indicate either a single or a composite (compound) primary key.
|
||||
* `@PrimaryKeyClass` - applied at the class level to indicate this class is a compound primary key class.
|
||||
Requires to be referenced with `@PrimaryKey` in the entity class.
|
||||
* `@Transient` - by default all private fields are mapped to the row, this annotation excludes the field
|
||||
where it is applied from being stored in the database.
|
||||
* `@Column` - applied at the field level. Describes the column name as it will be represented in the Cassandra table
|
||||
thus allowing the name to be different than the field name of the class.
|
||||
* `@Indexed` - applied at the field level. Describes the index to be created at session initialization.
|
||||
* `@SASI` - applied at the field level. Allows SASI index creation during session initialization.
|
||||
* `@CassandraType` - applied at the field level to specify a Cassandra data type. Types are derived from
|
||||
the declaration by default.
|
||||
* `@UserDefinedType` - applied at the type level to specify a Cassandra user-defined data type (UDT). Types are derived
|
||||
from the declaration by default.
|
||||
* `@CassandraType` - applied at the field level to specify a Cassandra data type.
|
||||
Types are derived from the declaration by default.
|
||||
* `@UserDefinedType` - applied at the type level to specify a Cassandra User-defined Data Type (UDT).
|
||||
Types are derived from the declaration by default.
|
||||
|
||||
The mapping metadata infrastructure is defined in the separate, spring-data-commons project that is technology agnostic.
|
||||
The mapping metadata infrastructure is defined in the separate, spring-data-commons project that is both
|
||||
technology and data store agnostic.
|
||||
|
||||
Here is an example of a more complex mapping.
|
||||
|
||||
@@ -486,11 +492,11 @@ public class Person {
|
||||
@UserDefinedType("address")
|
||||
public class Address {
|
||||
|
||||
private String city;
|
||||
|
||||
@CassandraType(type = Name.VARCHAR)
|
||||
private String street;
|
||||
|
||||
private String city;
|
||||
|
||||
private Set<String> zipcodes;
|
||||
|
||||
@CassandraType(type = Name.SET, typeArguments = Name.BIGINT)
|
||||
@@ -506,14 +512,15 @@ See the <<cassandra.connectors,configuration chapter>> for how to configure a `U
|
||||
|
||||
==== Index creation
|
||||
|
||||
You can annotate particular entity properties with `@Indexed` or `@SASI` if you whish to create secondary indexes on application
|
||||
startup. Index creation will create simple secondary indexes for scalar types, user-defined, and collection types.
|
||||
You can annotate particular entity properties with `@Indexed` or `@SASI` if you wish to create Secondary Indexes
|
||||
on application startup. Index creation will create simple Secondary Indexes for scalar types, user-defined,
|
||||
and collection types.
|
||||
|
||||
You can configure a SASI index to apply an analyzer such as `StandardAnalyzer` or `NonTokenizingAnalyzer` via
|
||||
You can configure a SASI Index to apply an analyzer such as `StandardAnalyzer` or `NonTokenizingAnalyzer` via
|
||||
`@StandardAnalyzed` respective `@NonTokenizingAnalyzed`.
|
||||
|
||||
Map types distinguish between `ENTRY`, `KEYS` and `VALUES` indexes. Index creation derives the index type from the
|
||||
annotated element:
|
||||
Map types distinguish between `ENTRY`, `KEYS` and `VALUES` Indexes. Index creation derives the Index type
|
||||
from the annotated element:
|
||||
|
||||
.Variants of map indexing
|
||||
====
|
||||
@@ -542,12 +549,13 @@ public class Person {
|
||||
|
||||
WARNING: Index creation on session initialization may have a severe performance impact on application startup.
|
||||
|
||||
|
||||
[[cassandra.mapping.explicit-converters]]
|
||||
=== Overriding Mapping with explicit Converters
|
||||
|
||||
When storing and querying your objects it is convenient to have a `CassandraConverter` instance handle the mapping
|
||||
of all Java types to Rows. However, sometimes you may want the `CassandraConverter` to do most of the work but
|
||||
still allow you to selectively handle the conversion for a particular type, or to optimize performance.
|
||||
of all Java types to Rows. However, sometimes you may want the `CassandraConverter` to do most of the work
|
||||
but still allow you to selectively handle the conversion for a particular type, or to optimize performance.
|
||||
|
||||
To selectively handle the conversion yourself, register one or more `org.springframework.core.convert.converter.Converter`
|
||||
instances with the `CassandraConverter`.
|
||||
@@ -564,9 +572,10 @@ Below is an example of a Spring `Converter` implementation that converts from a
|
||||
public class PersonReadConverter implements Converter<Row, Person> {
|
||||
|
||||
public Person convert(Row source) {
|
||||
Person p = new Person(row.getString("id"));
|
||||
p.setAge(source.getInt("age");
|
||||
return p;
|
||||
Person person = new Person(row.getString("id"));
|
||||
person.setAge(source.getInt("age");
|
||||
return person;
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
@@ -3,31 +3,33 @@
|
||||
|
||||
Spring Data for Apache Cassandra 2.0 introduces a set of breaking changes when upgrading from earlier versions:
|
||||
|
||||
* Merge of Spring CQL and Spring Data Cassandra.
|
||||
* Separate asynchronous and synchronous operations in `CqlOperations` and `CassandraOperations` into dedicated interfaces and templates.
|
||||
* Revise `CqlTemplate` API to align with `JdbcTemplate`.
|
||||
* Remove CassandraOperations.selectBySimpleIds.
|
||||
* Better names for CassandraRepository.
|
||||
* Remove own `ConsistencyLevel` and `RetryPolicy` types in favor of DataStax `ConsistencyLevel` and `RetryPolicy`.
|
||||
* Refactor CQL specifications to value objects/configurators.
|
||||
* Refactor `QueryOptions` to immutable objects.
|
||||
* Refactor `CassandraPersistentProperty` to single-column.
|
||||
* Merged the `spring-cql` and `spring-data-cassandra` modules into a single module.
|
||||
* Separated asynchronous and synchronous operations in `CqlOperations` and `CassandraOperations`
|
||||
into dedicated interfaces and templates.
|
||||
* Revised the `CqlTemplate` API to align with `JdbcTemplate`.
|
||||
* Removed the `CassandraOperations.selectBySimpleIds` method.
|
||||
* Used better names for `CassandraRepository`.
|
||||
* Removed SD Cassandra `ConsistencyLevel` and `RetryPolicy` types in favor of
|
||||
DataStax `ConsistencyLevel` and `RetryPolicy` types.
|
||||
* Refactored CQL specifications to value objects/configurators.
|
||||
* Refactored `QueryOptions` to be immutable objects.
|
||||
* Refactored `CassandraPersistentProperty` to single-column.
|
||||
|
||||
== Deprecations
|
||||
|
||||
* `QueryOptionsBuilder.readTimeout(long, TimeUnit)` in favor of `QueryOptionsBuilder.readTimeout(Duration)`.
|
||||
* `CustomConversions` in favor of `CassandraCustomConversions`.
|
||||
* `BasicCassandraMappingContext` in favor of `CassandraMappingContext`.
|
||||
* `o.s.d.c.core.cql.CachedPreparedStatementCreator` in favor of `o.s.d.c.core.cql.support.CachedPreparedStatementCreator`.
|
||||
* `CqlTemplate.getSession()` in favor of `getSessionFactory()`.
|
||||
* `CqlIdentifier.cqlId(…)` and `KeyspaceIdentifier.ksId(…)` in favor of `.of(…)` methods.
|
||||
* Constructors of `QueryOptions` in favor of their builders.
|
||||
* `TypedIdCassandraRepository` in favor of `CassandraRepository`
|
||||
* Deprecated `QueryOptionsBuilder.readTimeout(long, TimeUnit)` in favor of `QueryOptionsBuilder.readTimeout(Duration)`.
|
||||
* Deprecated `CustomConversions` in favor of `CassandraCustomConversions`.
|
||||
* Deprecated `BasicCassandraMappingContext` in favor of `CassandraMappingContext`.
|
||||
* Deprecated `o.s.d.c.core.cql.CachedPreparedStatementCreator` in favor of `o.s.d.c.core.cql.support.CachedPreparedStatementCreator`.
|
||||
* Deprecated `CqlTemplate.getSession()` in favor of `getSessionFactory()`.
|
||||
* Deprecated `CqlIdentifier.cqlId(…)` and `KeyspaceIdentifier.ksId(…)` in favor of `.of(…)` methods.
|
||||
* Deprecated constructors of `QueryOptions` in favor of their builders.
|
||||
* Deprecated `TypedIdCassandraRepository` in favor of `CassandraRepository`
|
||||
|
||||
== Merge of Spring CQL and Spring Data Cassandra
|
||||
== Merged Spring CQL and Spring Data Cassandra modules
|
||||
|
||||
Spring CQL and Spring Data Cassandra are now merged into a single module. The standalone `spring-cql` module is no longer available.
|
||||
Find all types merged into `spring-data-cassandra`.
|
||||
Spring CQL and Spring Data Cassandra are now merged into a single module. The standalone `spring-cql` module
|
||||
is no longer available. Find all types merged into `spring-data-cassandra`.
|
||||
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
@@ -45,7 +47,7 @@ Find all types merged into `spring-data-cassandra`.
|
||||
With the merge, we merged all CQL packages into Spring Data Cassandra:
|
||||
|
||||
* Moved `o.s.d.cql` into `o.s.d.cassandra.core.cql`.
|
||||
* Merge `o.s.d.cql` with `o.s.d.cassandra.config` and flatten XML and Java subpackages.
|
||||
* Merged `o.s.d.cql` with `o.s.d.cassandra.config` and flattened XML and Java subpackages.
|
||||
* Moved `CassandraExceptionTranslator` and `CqlExceptionTranslator` to `o.s.d.c.core.cql`.
|
||||
* Moved Cassandra exceptions `o.s.d.c.support.exception` to `o.s.d.cassandra`
|
||||
* Moved `o.s.d.c.convert` to `o.s.d.c.core.convert` (affects converters)
|
||||
@@ -56,20 +58,21 @@ With the merge, we merged all CQL packages into Spring Data Cassandra:
|
||||
|
||||
We split `CqlTemplate` and `CassandraTemplate` in two ways:
|
||||
|
||||
* `CassandraTemplate` no longer is a `CqlTemplate` but uses an instance which allows
|
||||
reuse and fine-grained control over fetchsize, consistency levels and retry policies.
|
||||
You can obtain the `CqlOperations` via `CassandraTemplate.getCqlOperations()`. Because of the change,
|
||||
dependency injection of `CqlTemplate` requires additional bean setup.
|
||||
* `CqlTemplate` now reflects basic CQL operations instead of mixing high-level and low-level API (such as `count(…)` vs. `execute(…)`)
|
||||
and the reduced method set is aligned with Spring Frameworks's `JdbcTemplate` with its callback interfaces.
|
||||
* Asynchronous methods are re-implemented on `AsyncCqlTemplate` and `AsyncCassandraTemplate` by using
|
||||
`ListenableFuture`. We removed `Cancellable` and the various async callback listeners. `ListenableFuture` is a flexible
|
||||
approach and allows transition into a `CompletableFuture`.
|
||||
* `CassandraTemplate` no longer is a `CqlTemplate` but uses an instance which allows reuse and fine-grained control
|
||||
over fetch size, consistency levels and retry policies. You can obtain the `CqlOperations` via
|
||||
`CassandraTemplate.getCqlOperations()`. Because of the change, dependency injection of `CqlTemplate` requires
|
||||
additional bean setup.
|
||||
* `CqlTemplate` now reflects basic CQL operations instead of mixing high-level and low-level API (such as `count(…)`
|
||||
vs. `execute(…)`) and the reduced method set is aligned with Spring Frameworks's `JdbcTemplate` with its convenient
|
||||
callback interfaces.
|
||||
* Asynchronous methods are re-implemented on `AsyncCqlTemplate` and `AsyncCassandraTemplate` by using `ListenableFuture`.
|
||||
We removed `Cancellable` and the various async callback listeners. `ListenableFuture` is a flexible approach
|
||||
and allows transition into a `CompletableFuture`.
|
||||
|
||||
== Remove CassandraOperations.selectBySimpleIds
|
||||
== Removed CassandraOperations.selectBySimpleIds
|
||||
|
||||
The method was removed because it did not support complex Ids. The newly introduced query DSL allows
|
||||
mapped and complex id's for single column Id's:
|
||||
The method was removed because it did not support complex Ids. The newly introduced query DSL allows mapped
|
||||
and complex id's for single column Id's:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -78,28 +81,33 @@ cassandraTemplate.select(Query.query(Criteria.where("id").in(…)), Person.class
|
||||
|
||||
== Better names for CassandraRepository
|
||||
|
||||
We renamed `CassandraRepository` and `TypedIdCassandraRepository` to align naming with other Spring Data modules:
|
||||
We renamed `CassandraRepository` and `TypedIdCassandraRepository` to align SD Cassandra naming with other
|
||||
Spring Data modules:
|
||||
|
||||
* Rename `CassandraRepository` to `MapIdCassandraRepository`
|
||||
* Rename `TypedIdCassandraRepository` to `CassandraRepository`
|
||||
* Introduce `TypedIdCassandraRepository` extending `CassandraRepository` as deprecated type to ease migration
|
||||
* Renamed `CassandraRepository` to `MapIdCassandraRepository`
|
||||
* Renamed `TypedIdCassandraRepository` to `CassandraRepository`
|
||||
* Introduced `TypedIdCassandraRepository` extending `CassandraRepository` as deprecated type to ease migration
|
||||
|
||||
== Remove own `ConsistencyLevel` and `RetryPolicy` types in favor of DataStax `ConsistencyLevel` and `RetryPolicy`
|
||||
== Removed SD Cassandra `ConsistencyLevel` and `RetryPolicy` types in favor of DataStax `ConsistencyLevel` and `RetryPolicy` types
|
||||
|
||||
Our own `ConsistencyLevel` and `RetryPolicy` are gone now. Please use the types provided by the DataStax driver. Our own
|
||||
types restricted the available features and didn't allow native drivers feature usage. These types required an update each time newer functionality was introduced by the driver.
|
||||
SD Cassandra `ConsistencyLevel` and `RetryPolicy` have been removed. Please use the types provided by
|
||||
the DataStax driver directly.
|
||||
|
||||
== Refactor CQL specifications to value objects/configurators
|
||||
The SD Cassandra types restricted usage of available features provided in and allowed by the Cassandra native driver.
|
||||
As a result, the SD Cassandra's types required an update each time newer functionality was introduced by the driver.
|
||||
|
||||
== Refactored CQL specifications to value objects/configurators
|
||||
|
||||
CQL specification types are now value types as much as possible (such as `FieldSpecification`, `AlterColumnSpecification`)
|
||||
and object are constructed via static factory methods. This allows immutability for simple value objects. Configurator objects
|
||||
(such as `AlterTableSpecification`) that operate on mandatory properties like a table name, keyspace name, are initially
|
||||
constructed through a a static factory method and allow further configuration until the desired state is created.
|
||||
and objects are constructed via static factory methods. This allows immutability for simple value objects.
|
||||
Configurator objects (such as `AlterTableSpecification`) that operate on mandatory properties like a table name,
|
||||
keyspace name, are initially constructed through a a static factory method and allow further configuration until
|
||||
the desired state is created.
|
||||
|
||||
== Refactor `QueryOptions` to immutable objects
|
||||
== Refactored `QueryOptions` to be immutable objects
|
||||
|
||||
`QueryOptions` and `WriteOptions` are now immutable and can be created through builders. Methods
|
||||
accepting `QueryOptions` enforce non-null objects which are available from static `empty()` factory methods.
|
||||
`QueryOptions` and `WriteOptions` are now immutable and can be created through builders. Methods accepting
|
||||
`QueryOptions` enforce non-null objects which are available from static `empty()` factory methods.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -112,10 +120,11 @@ QueryOptions queryOptions = QueryOptions.builder()
|
||||
.build();
|
||||
----
|
||||
|
||||
== Refactor `CassandraPersistentProperty` to single-column
|
||||
== Refactored `CassandraPersistentProperty` to single-column
|
||||
|
||||
You are only affected by this change if you operate on the mapping model directly.
|
||||
|
||||
`CassandraPersistentProperty` allowed previously multiple column names to be bound for composite primary key use.
|
||||
Columns of a `CassandraPersistentProperty` are now reduced to a single column. Resolve composite primary keys mapped
|
||||
to a class via `MappingContext.getRequiredPersistentEntity(…)`.
|
||||
Columns of a `CassandraPersistentProperty` are now reduced to a single column. Resolved composite primary keys
|
||||
mapped to a class via `MappingContext.getRequiredPersistentEntity(…)`.
|
||||
|
||||
|
||||
@@ -1,21 +1,39 @@
|
||||
[[cassandra.reactive.repositories]]
|
||||
= Reactive Cassandra repositories
|
||||
= Reactive Cassandra Repositories
|
||||
|
||||
|
||||
[[cassandra.reactive.repositories.intro]]
|
||||
== Introduction
|
||||
|
||||
This chapter will point out the specialties for reactive repository support for Apache Cassandra. This builds on the core repository support explained in <<cassandra.repositories>>. So make sure you've got a sound understanding of the basic concepts explained there.
|
||||
This chapter will outline the specialties handled by the reactive _Repository_ support for Apache Cassandra.
|
||||
This builds on the core _Repository_ infrastructure explained in <<cassandra.repositories>>, so make sure
|
||||
you have a good understanding of the basic concepts explained there.
|
||||
|
||||
Reactive usage is broken up into two phases: Composition and Execution.
|
||||
|
||||
Calling _Repository_ methods lets you compose a reactive sequence by obtaining ``Publisher``s and applying operators.
|
||||
No I/O happens until now. Passing the reactive sequence to a reactive execution infrastructure,
|
||||
such as http://docs.spring.io/spring-framework/docs/{springVersion}/spring-framework-reference/web.html#web-reactive[Spring WebFlux]
|
||||
or http://vertx.io/docs/vertx-reactive-streams/java/[Vert.x]), will subscribe to the publisher and initiate
|
||||
the actual execution.
|
||||
|
||||
Reactive usage splits into two phases: Composition and execution. Calling repository methods lets you compose a reactive sequence by obtaining ``Publisher``s and applying operators. No I/O happens until now. Passing the reactive sequence to a reactive execution infrastructure (such as http://docs.spring.io/spring-framework/docs/{springVersion}/spring-framework-reference/web.html#web-reactive[Spring WebFlux] or http://vertx.io/docs/vertx-reactive-streams/java/[Vert.x]) will subscribe to the publisher and initiate the actual execution.
|
||||
|
||||
[[cassandra.reactive.repositories.libraries]]
|
||||
== Reactive Composition Libraries
|
||||
|
||||
The reactive space offers various reactive composition libraries. The most common libraries are https://github.com/ReactiveX/RxJava[RxJava] and https://projectreactor.io/[Project Reactor].
|
||||
The reactive space offers various reactive composition libraries. The most common libraries are
|
||||
https://github.com/ReactiveX/RxJava[RxJava] and https://projectreactor.io/[Project Reactor].
|
||||
|
||||
Spring Data Apache Cassandra is built on top of the https://github.com/datastax/java-driver[DataStax Cassandra] driver. It's not a reactive driver but the asynchronous capabilities allow adoption and exposing `Publisher` APIs to provide maximal interoperability relying on the http://www.reactive-streams.org/[Reactive Streams] initiative. Static APIs such as `ReactiveCassandraOperations` are provided by using Project Reactor's `Flux` and `Mono` types. Project Reactor offers various adapters to convert reactive wrapper types (`Flux` to `Observable` and vice versa) but conversion can easily clutter your code.
|
||||
Spring Data for Apache Cassandra is built on top of the https://github.com/datastax/java-driver[DataStax Cassandra Driver].
|
||||
The driver is not reactive but the asynchronous capabilities allow us to adopt and expose the `Publisher` APIs
|
||||
in order to provide maximum interoperability by relying on the http://www.reactive-streams.org/[Reactive Streams] initiative.
|
||||
Static APIs, such as `ReactiveCassandraOperations`, are provided by using Project Reactor's `Flux` and `Mono` types.
|
||||
Project Reactor offers various adapters to convert reactive wrapper types (`Flux` to `Observable` and vice versa)
|
||||
but conversion can easily clutter your code.
|
||||
|
||||
Spring Data's Repository abstraction is a dynamic API, mostly defined by you and your requirements, as you're declaring query methods. Reactive Cassandra repositories can be either implemented using RxJava or Project Reactor wrapper types by simply extending from one of the library-specific repository interfaces:
|
||||
Spring Data's _Repository_ abstraction is a dynamic API, mostly defined by you and your requirements,
|
||||
as you are declaring query methods. Reactive Cassandra _Repositories_ can be either implemented using RxJava
|
||||
or Project Reactor wrapper types by simply extending from one of the library-specific repository interfaces:
|
||||
|
||||
* `ReactiveCrudRepository`
|
||||
* `ReactiveSortingRepository`
|
||||
@@ -24,11 +42,12 @@ Spring Data's Repository abstraction is a dynamic API, mostly defined by you and
|
||||
|
||||
Spring Data converts reactive wrapper types behind the scenes so that you can stick to your favorite composition library.
|
||||
|
||||
|
||||
[[cassandra.reactive.repositories.usage]]
|
||||
== Usage
|
||||
|
||||
To access domain entities stored in Apache Cassandra, you can leverage Spring Data's sophisticated Repository support
|
||||
that eases implementing DAOs quite significantly. To do so, simply create an interface for your Repository:
|
||||
To access entities stored in Apache Cassandra, you can leverage Spring Data's sophisticated _Repository_ support,
|
||||
which eases implementing DAOs quite significantly. To do so, simply create an interface for your _Repository_:
|
||||
|
||||
.Sample Person entity
|
||||
====
|
||||
@@ -47,9 +66,9 @@ public class Person {
|
||||
----
|
||||
====
|
||||
|
||||
We have a simple domain object here. Note that the entity has a property named `id` of type `String`.
|
||||
The default serialization mechanism used in `CassandraTemplate` (which is backing the Repository support)
|
||||
regards properties named id as row id.
|
||||
We have a simple domain object here. Note that the entity has a property named "`id`" of type `String`.
|
||||
The default serialization mechanism used in `CassandraTemplate` (which is backing the _Repository_ support)
|
||||
regards properties named "id" as the row id.
|
||||
|
||||
.Basic repository interface to persist Person entities
|
||||
====
|
||||
@@ -69,7 +88,9 @@ public interface ReactivePersonRepository extends ReactiveSortingRepository<Pers
|
||||
----
|
||||
====
|
||||
|
||||
For JavaConfig use the `@EnableReactiveCassandraRepositories` annotation. The annotation carries the very same attributes like the namespace element. If no base package is configured the infrastructure will scan the package of the annotated configuration class.
|
||||
For JavaConfig, use the `@EnableReactiveCassandraRepositories` annotation. The annotation carries the very same attributes
|
||||
like the corresponding XML namespace element. If no base package is configured the infrastructure will scan the package
|
||||
of the annotated configuration class.
|
||||
|
||||
.JavaConfig for repositories
|
||||
====
|
||||
@@ -91,7 +112,9 @@ class ApplicationConfig extends AbstractReactiveCassandraConfiguration {
|
||||
----
|
||||
====
|
||||
|
||||
As our domain repository extends `ReactiveSortingRepository` it provides you with CRUD operations as well as methods for sorted access to the entities. Working with the repository instance is just a matter of dependency injecting it into a client.
|
||||
Since our domain _Repository_ extends `ReactiveSortingRepository`, it provides you with CRUD operations
|
||||
as well as methods for sorted access to the entities. Working with the _Repository_ instance is just a matter of
|
||||
dependency injecting it into a client.
|
||||
|
||||
.Sorted access to Person entities
|
||||
====
|
||||
@@ -112,11 +135,13 @@ public class PersonRepositoryTests {
|
||||
[[cassandra.reactive.repositories.features]]
|
||||
== Features
|
||||
|
||||
Spring Data's Reactive Cassandra support comes with the same set of features as <<cassandra.repositories,imperative repositories>>.
|
||||
Spring Data's Reactive Cassandra support comes with the same set of features as
|
||||
<<cassandra.repositories,imperative repositories>>.
|
||||
|
||||
Following features are supported:
|
||||
The following features are supported:
|
||||
|
||||
* Query Methods using <<cassandra.repositories.queries,String queries and Query Derivation>>
|
||||
* <<projections>>
|
||||
|
||||
NOTE: Query methods must return a reactive type. Resolved types (`User` vs. `Mono<User>`) are not supported.
|
||||
|
||||
|
||||
@@ -3,37 +3,41 @@
|
||||
|
||||
The reactive Cassandra support contains a wide range of features which are summarized below.
|
||||
|
||||
* Spring configuration support using Java-based `@Configuration` classes
|
||||
* `ReactiveCqlTemplate` helper class that increases productivity by handling common Cassandra operations properly.
|
||||
* `ReactiveCassandraTemplate` helper class that increases productivity using `ReactiveCassandraOperations in a reactive manner. Includes integrated object mapping between `Documents and POJOs.
|
||||
* Spring configuration support using Java-based `@Configuration` classes.
|
||||
* `ReactiveCqlTemplate` helper class that increases productivity by handling common Cassandra data access operations properly.
|
||||
* `ReactiveCassandraTemplate` helper class that increases productivity using `ReactiveCassandraOperations in a reactive manner.
|
||||
Includes integrated object mapping between tables and POJOs.
|
||||
* Exception translation into Spring's portable http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#dao-exceptions[Data Access Exception Hierarchy].
|
||||
* Feature rich object mapping integrated with Spring's http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#core-convert[Conversion Service].
|
||||
* Java-based Query, Criteria, and Update DSLs.
|
||||
* Automatic implementation of `Repository` interfaces including support for custom finder methods.
|
||||
|
||||
For most data oriented tasks you will use the `ReactiveCassandraTemplate` or the `Repository` support, which leverage the
|
||||
rich mapping functionality. `ReactiveCqlTemplate` is commonly used to increment counters or perform ad-hoc CRUD
|
||||
operations. `ReactiveCqlTemplate` also provides callback methods making it easy to get a hold of low-level API objects
|
||||
such as `com.datastax.driver.core.Session` allowing you to communicate directly with Cassandra. Spring Data for Apache Cassandra
|
||||
uses consistent naming conventions on objects in various APIs to those found in the DataStax Java Driver so that they
|
||||
are familiar and so you can map your existing knowledge onto the Spring APIs.
|
||||
For most data-oriented tasks you will use the `ReactiveCassandraTemplate` or the _Repository_ support, which leverage
|
||||
the rich object mapping functionality. `ReactiveCqlTemplate` is commonly used to increment counters or perform ad-hoc
|
||||
CRUD operations. `ReactiveCqlTemplate` also provides callback methods making it easy to get a hold of low-level
|
||||
API objects, such as `com.datastax.driver.core.Session`, allowing you to communicate directly with Cassandra.
|
||||
Spring Data for Apache Cassandra uses consistent naming conventions on objects in various APIs to those found
|
||||
in the DataStax Java Driver so that they are immediately familiar and so you can map your existing knowledge
|
||||
onto the Spring APIs.
|
||||
|
||||
|
||||
[[cassandra.reactive.getting-started]]
|
||||
== Getting Started
|
||||
|
||||
Spring Apache Cassandra support requires Apache Cassandra 2.1 or higher, Datastax Java Driver 3.0 or higher
|
||||
and Java SE 8 or higher. An easy way to bootstrap setting up a working environment is to create a Spring-based project
|
||||
in http://spring.io/tools/sts[STS].
|
||||
Spring Data for Apache Cassandra support requires Apache Cassandra 2.1 or higher, Datastax Java Driver 3.0 or higher
|
||||
and Java SE 8 or higher. An easy way to setup and bootstrap a working environment is to create a Spring-based project
|
||||
in http://spring.io/tools/sts[STS] or use http://start.spring.io/[Spring Initializer].
|
||||
|
||||
First you need to set up a running Apache Cassandra server. Refer to
|
||||
the http://cassandra.apache.org/doc/latest/getting_started/index.html[Apache Cassandra Quick Start guide]
|
||||
for an explanation on how to startup Apache Cassandra. Once installed starting Cassandra is typically a matter of
|
||||
First you need to set up a running Apache Cassandra server. Refer to the
|
||||
http://cassandra.apache.org/doc/latest/getting_started/index.html[Apache Cassandra Quick Start Guide]
|
||||
for an explanation on how to startup Apache Cassandra. Once installed, starting Cassandra is typically a matter of
|
||||
executing the following command: `CASSANDRA_HOME/bin/cassandra -f`
|
||||
|
||||
To create a Spring project in STS go to File -> New -> Spring Template Project -> Simple Spring Utility Project ->
|
||||
press Yes when prompted. Then enter a project and a package name such as org.spring.cassandra.example.
|
||||
To create a Spring project in STS go to File -> New -> Spring Template Project -> Simple Spring Utility Project
|
||||
and press Yes when prompted. Then enter a project and a package name such as `org.spring.data.cassandra.example`.
|
||||
|
||||
Then add dependency or your _pom.xml `dependencies` section.
|
||||
|
||||
Then add the following to pom.xml dependencies section.
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
<dependencies>
|
||||
@@ -47,7 +51,7 @@ Then add the following to pom.xml dependencies section.
|
||||
</dependencies>
|
||||
----
|
||||
|
||||
Also change the version of Spring in the pom.xml to be
|
||||
Also change the version of Spring in the _pom.xml_ to be
|
||||
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
@@ -55,7 +59,7 @@ Also change the version of Spring in the pom.xml to be
|
||||
----
|
||||
|
||||
If using a milestone release instead of a GA release, you will also need to add the location of the Spring Milestone
|
||||
repository for Maven to your `pom.xml` which is at the same level of your <dependencies/> element.
|
||||
repository for Maven to your _pom.xml_, which is at the same level of your `<dependencies/>` element.
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
@@ -70,9 +74,9 @@ repository for Maven to your `pom.xml` which is at the same level of your <depen
|
||||
|
||||
The repository is also http://repo.spring.io/milestone/org/springframework/data/[browseable here].
|
||||
|
||||
You can also browse the Spring repositories https://repo.spring.io/webapp/#/home[here].
|
||||
You can browse all Spring repositories https://repo.spring.io/webapp/#/home[here].
|
||||
|
||||
Now we will create a simple Java application that stores and reads a domain object to/from Cassandra.
|
||||
Now, we will create a simple Java application that stores and reads a domain object to/from Cassandra.
|
||||
|
||||
First, create a simple domain object class to persist.
|
||||
|
||||
@@ -172,11 +176,13 @@ public class CassandraApplication {
|
||||
|
||||
Even in this simple example, there are a few things to observe.
|
||||
|
||||
* A fully synchronous flow does not benefit from reactive infrastructure as a reactive programming model requires synchronization
|
||||
* A fully synchronous flow does not benefit from a reactive infrastructure as a reactive programming model
|
||||
requires synchronization.
|
||||
* You can create an instance of `ReactiveCassandraTemplate` with a Cassandra `Session`, obtained from `Cluster`.
|
||||
* You must annotate your POJO as a Cassandra `@Table` and also annotate the `@PrimaryKey`. Optionally, you can
|
||||
override these mapping names to match your Cassandra database table and column names.
|
||||
* You can either use a CQL String or the DataStax `QueryBuilder` API to construct your queries.
|
||||
* You must annotate your POJO as a Cassandra `@Table` and also annotate the `@PrimaryKey`.
|
||||
Optionally, you can override these mapping names to match your Cassandra database table and column names.
|
||||
* You can either use raw CQL or the DataStax `QueryBuilder` API to construct your queries.
|
||||
|
||||
|
||||
[[cassandra.reactive.examples-repo]]
|
||||
== Examples Repository
|
||||
@@ -184,11 +190,12 @@ override these mapping names to match your Cassandra database table and column n
|
||||
There is a https://github.com/spring-projects/spring-data-examples[Github repository with several examples] that you
|
||||
can download and play around with to get a feel for how the library works.
|
||||
|
||||
|
||||
[[cassandra.connectors]]
|
||||
== Connecting to Cassandra with Spring
|
||||
|
||||
One of the first tasks when using Apache Cassandra and Spring is to create a `com.datastax.driver.core.Session` object
|
||||
using the Spring IoC container. There are two main ways to do this, either using Java-based bean metadata or XML-based
|
||||
using the Spring container. There are two main ways to do this, either using Java-based bean metadata or XML-based
|
||||
bean metadata. These are discussed in the following sections.
|
||||
|
||||
NOTE: For those not familiar with how to configure the Spring container using Java-based bean metadata instead of
|
||||
@@ -196,8 +203,9 @@ XML-based metadata, see the high-level introduction in the reference docs
|
||||
http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/new-in-3.0.html#new-java-configuration[here]
|
||||
as well as the detailed documentation http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/beans.html#beans-java-instantiating-container[here].
|
||||
|
||||
|
||||
[[cassandra.cassandra-reactive-java-config]]
|
||||
=== Registering a Session instance using Java based metadata
|
||||
=== Registering a Session instance using Java-based metadata
|
||||
|
||||
You can configure Reactive Cassandra support via <<cassandra.cassandra-java-config,Java Configuration classes>>.
|
||||
Reactive Cassandra support adapts a `Session` to provide a reactive execution model on top of an asynchronous driver.
|
||||
@@ -205,8 +213,8 @@ Reactive Cassandra support adapts a `Session` to provide a reactive execution mo
|
||||
A reactive `Session` is configured similar to an imperative `Session`. We provide supporting configuration classes
|
||||
that come with predefined defaults and require only environment-specific information to configure Spring Data for
|
||||
Apache Cassandra. The base class for reactive support is `AbstractReactiveCassandraConfiguration`. This configuration
|
||||
class extends the imperative `AbstractCassandraConfiguration` and so reactive support also configures imperative API
|
||||
support.
|
||||
class extends the imperative `AbstractCassandraConfiguration` and so the reactive support will also configure
|
||||
the imperative API support as well.
|
||||
|
||||
.Registering Spring Data for Apache Cassandra beans using `AbstractReactiveCassandraConfiguration`
|
||||
====
|
||||
@@ -232,39 +240,42 @@ public class AppConfig extends AbstractReactiveCassandraConfiguration {
|
||||
----
|
||||
====
|
||||
|
||||
This configuration class is schema-management-enabled to create CQL objects during statup. See <<cassandra.schema-management>>
|
||||
for further details.
|
||||
This configuration class is schema-management-enabled to create CQL objects during startup.
|
||||
See <<cassandra.schema-management>> for further details.
|
||||
|
||||
|
||||
[[cassandra.reactive.cql-template]]
|
||||
== ReactiveCqlTemplate
|
||||
|
||||
The `ReactiveCqlTemplate` class is the central class in the CQL core package. It handles the creation and release of resources.
|
||||
It performs the basic tasks of the core CQL workflow such as statement creation and execution, leaving application code
|
||||
to provide CQL and extract results. The `ReactiveCqlTemplate` class executes CQL queries and update statements, performs
|
||||
iteration over ``ResultSet``s and extraction of returned parameter values. It also catches CQL exceptions and translates
|
||||
them to the generic, more informative, exception hierarchy defined in the `org.springframework.dao` package.
|
||||
The `ReactiveCqlTemplate` class is the central class in the core CQL package. It handles the creation and release
|
||||
of resources. It performs the basic tasks of the core CQL workflow such as statement creation and execution,
|
||||
leaving application code to provide CQL and extract results. The `ReactiveCqlTemplate` class executes CQL queries
|
||||
and update statements, performs iteration over ``ResultSet``s and extraction of returned parameter values.
|
||||
It also catches CQL exceptions and translates them into the generic, more informative, exception hierarchy defined in
|
||||
the `org.springframework.dao` package.
|
||||
|
||||
When you use the `ReactiveCqlTemplate` for your code, you only need to implement callback interfaces, giving them a clearly
|
||||
defined contract. The `ReactivePreparedStatementCreator` callback interface creates a prepared statement given a `Connection`
|
||||
provided by this class, providing CQL and any necessary parameters. The `RowCallbackHandler` interface extracts values
|
||||
from each row of a `ReactiveResultSet`.
|
||||
When you use the `ReactiveCqlTemplate` in your code, you only need to implement callback interfaces, which have a
|
||||
very clearly defined contract. Given a `Connection`, the `ReactivePreparedStatementCreator` callback interface
|
||||
creates a prepared statement with the provided CQL and any necessary parameter argumnents. The `RowCallbackHandler`
|
||||
interface extracts values from each row of a `ReactiveResultSet`.
|
||||
|
||||
The `ReactiveCqlTemplate` can be used within a DAO implementation through direct instantiation with a `ReactiveSessionFactory`
|
||||
reference, or be configured in a Spring IoC container and given to DAOs as a bean reference. `ReactiveCqlTemplate` is a foundational building
|
||||
block for <<cassandra.reactive.template,`ReactiveCassandraTemplate`>>.
|
||||
reference, or be configured in the Spring container and given to DAOs as a bean reference. `ReactiveCqlTemplate` is
|
||||
a foundational building block for <<cassandra.reactive.template,`ReactiveCassandraTemplate`>>.
|
||||
|
||||
All CQL issued by this class is logged at the `DEBUG` level under the category corresponding to the fully-qualified
|
||||
class name of the template instance (typically `ReactiveCqlTemplate`, but it may be different if you are using
|
||||
a custom subclass of the `ReactiveCqlTemplate` class).
|
||||
|
||||
All CQL issued by this class is logged at the `DEBUG` level under the category corresponding to the fully qualified class
|
||||
name of the template instance (typically `ReactiveCqlTemplate`, but it may be different if you are using a custom subclass of the
|
||||
`ReactiveCqlTemplate` class).
|
||||
|
||||
[[cassandra.reactive.cql-template.examples]]
|
||||
=== Examples of `ReactiveCqlTemplate` class usage
|
||||
|
||||
This section provides some examples of `ReactiveCqlTemplate` class usage. These examples are not an exhaustive list of all of the
|
||||
functionality exposed by the `ReactiveCqlTemplate`; see the attendant javadocs for that.
|
||||
This section provides some examples of `ReactiveCqlTemplate` class usage. These examples are not an exhaustive list
|
||||
of all of the functionality exposed by the `ReactiveCqlTemplate`; see the attendant Javadocs for that.
|
||||
|
||||
[[cql-template.examples.query]]
|
||||
==== Querying (SELECT)
|
||||
==== Querying (SELECT) with `ReactiveCqlTemplate`
|
||||
Here is a simple query for getting the number of rows in a relation:
|
||||
|
||||
[source,java]
|
||||
@@ -324,8 +335,9 @@ Flux<Actor> actors = reactiveCqlTemplate.query(
|
||||
|
||||
If the last two snippets of code actually existed in the same application, it would make sense to remove the
|
||||
duplication present in the two `RowMapper` anonymous inner classes, and extract them out into a single class
|
||||
(typically a `static` nested class) that can then be referenced by DAO methods as needed. For example, it may
|
||||
be better to write the last code snippet as follows:
|
||||
(typically a `static` nested class) that can then be referenced by DAO methods as needed.
|
||||
|
||||
For example, it may be better to write the last code snippet as follows:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -347,10 +359,10 @@ enum ActorMapper implements RowMapper<Actor> {
|
||||
----
|
||||
|
||||
[[cassandra.reactive.cql-template.examples.update]]
|
||||
==== Updating (INSERT/UPDATE/DELETE) with ReactiveCqlTemplate
|
||||
==== Updating (INSERT/UPDATE/DELETE) with `ReactiveCqlTemplate`
|
||||
|
||||
You use the `execute(…)` method to perform insert, update and delete operations. Parameter values are usually
|
||||
provided as var args or alternatively as an object array.
|
||||
provided as var args or alternatively as an Object array.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -375,53 +387,57 @@ Mono<Boolean> applied = reactiveCqlTemplate.execute(
|
||||
|
||||
include::exception-translation.adoc[]
|
||||
|
||||
`ReactiveCqlTemplate` and `ReactiveCassandraTemplate` propagate exceptions as early as possible. Exceptions that occur during execution
|
||||
of the reactive sequence are emitted as error signals.
|
||||
`ReactiveCqlTemplate` and `ReactiveCassandraTemplate` propagate exceptions as early as possible. Exceptions that occur
|
||||
during execution of the reactive sequence are emitted as error signals.
|
||||
|
||||
|
||||
[[cassandra.reactive.template]]
|
||||
== Introduction to ReactiveCassandraTemplate
|
||||
|
||||
The `ReactiveCassandraTemplate` class, located in the package `org.springframework.data.cassandra`, is the central class
|
||||
in Spring's Cassandra support providing a rich feature set to interact with the database. The template offers
|
||||
convenience operations to create, update, delete and query Cassandra and provides a mapping between your domain objects
|
||||
and Cassandra rows.
|
||||
in Spring Data's Cassandra support providing a rich feature set to interact with the database. The template offers
|
||||
convenience data access operations to create, update, delete and query Cassandra, and provides a mapping between
|
||||
your domain objects and Cassandra table rows.
|
||||
|
||||
NOTE: Once configured, `ReactiveCassandraTemplate` is Thread-safe and can be reused across multiple instances.
|
||||
|
||||
The mapping between Cassandra rows and domain classes is done by delegating to an implementation
|
||||
of the `CassandraConverter` interface. Spring provides a default implementation, `MappingCassandraConverter`,
|
||||
but you can also write your own converter. Please refer to the section on <<mapping-chapter,Cassandra conversion>>
|
||||
The mapping between rows in a Cassandra table and domain classes is done by delegating to an implementation of
|
||||
the `CassandraConverter` interface. Spring provides a default implementation, `MappingCassandraConverter`,
|
||||
but you can also write your own custom converter. Please refer to the section on <<mapping-chapter,Cassandra conversion>>
|
||||
for more detailed information.
|
||||
|
||||
The `ReactiveCassandraTemplate` class implements the interface `ReactiveCassandraOperations`. In as much as possible, the methods
|
||||
on `ReactiveCassandraOperations` are named after methods available with Cassandra to make the API familiar to
|
||||
existing Cassandra developers who are familiar with Cassandra. For example, you will find methods such as "select",
|
||||
"insert", "delete", and "update". The design goal was to make it as easy as possible to transition between the use
|
||||
of the base Cassandra driver and `ReactiveCassandraOperations`. A major difference in between the two APIs is that
|
||||
`ReactiveCassandraOperations` can be passed domain objects instead of CQL and query objects.
|
||||
The `ReactiveCassandraTemplate` class implements the `ReactiveCassandraOperations` interface. In as much as possible,
|
||||
the methods in `ReactiveCassandraOperations` are named after methods available with Cassandra to make the API familiar
|
||||
to existing Cassandra developers who are familiar with Cassandra.
|
||||
|
||||
For example, you will find methods such as "select", "insert", "delete", and "update". The design goal was to make it
|
||||
as easy as possible to transition between the use of the base Cassandra driver and `ReactiveCassandraOperations`.
|
||||
A major difference between the two APIs is that `ReactiveCassandraOperations` can be passed domain objects instead of
|
||||
CQL and query objects.
|
||||
|
||||
NOTE: The preferred way to reference operations on a `ReactiveCassandraTemplate` instance is via its interface,
|
||||
`ReactiveCassandraOperations`.
|
||||
|
||||
The default converter implementation used by `ReactiveCassandraTemplate` is `MappingCassandraConverter`.
|
||||
While the `MappingCassandraConverter` can make use of additional metadata to specify the mapping of objects
|
||||
to rows it is also capable of converting objects that contain no additional metadata by using some conventions
|
||||
for the mapping of fields and table names. These conventions as well as the use of mapping annotations is explained
|
||||
in the <<mapping.chapter,Mapping chapter>>.
|
||||
While the `MappingCassandraConverter` can make use of additional metadata to specify the mapping of objects to rows
|
||||
it is also capable of converting objects that contain no additional metadata by using conventions for the mapping of
|
||||
fields and table names. These conventions as well as the use of mapping annotations is explained in the
|
||||
<<mapping.chapter,Mapping chapter>>.
|
||||
|
||||
Another central feature of `CassandraTemplate` is exception translation of exceptions thrown in the Cassandra
|
||||
Another central feature of `CassandraTemplate` is exception translation of exceptions thrown by the Cassandra
|
||||
Java driver into Spring's portable Data Access Exception hierarchy. Refer to the section on
|
||||
<<cassandra.exception,exception translation>> for more information.
|
||||
|
||||
Now let's look at a examples of how to work with the `CassandraTemplate` in the context of the Spring container.
|
||||
Now, let's look at examples of how to work with the `CassandraTemplate` in the context of the Spring container.
|
||||
|
||||
[[cassandra.reactive.template.instantiating]]
|
||||
=== Instantiating ReactiveCassandraTemplate
|
||||
|
||||
`ReactiveCassandraTemplate` should always be configured as a Spring Bean, although we show an example above where you can instantiate
|
||||
it directly. But for the purposes of this being a Spring module, lets assume we are using the Spring Container.
|
||||
`ReactiveCassandraTemplate` should always be configured as a Spring bean, although we show an example above
|
||||
where you can instantiate it directly. But, for the purposes of this being a Spring module, lets assume
|
||||
we are using the Spring container.
|
||||
|
||||
There are 2 easy ways to get a `ReactiveCassandraTemplate`, depending on how you load you Spring Application Context.
|
||||
There are 2 easy ways to get a `ReactiveCassandraTemplate`, depending on how you load you Spring `ApplicationContext`.
|
||||
|
||||
[float]
|
||||
==== Autowiring
|
||||
@@ -433,13 +449,13 @@ private ReactiveCassandraOperations reactiveCassandraOperations;
|
||||
----
|
||||
|
||||
Like all Spring Autowiring, this assumes there is only one bean of type `ReactiveCassandraOperations` in the `ApplicationContext`.
|
||||
If you have multiple `ReactiveCassandraTemplate` beans (which will be the case if you are working with multiple keyspaces
|
||||
If you have multiple `ReactiveCassandraTemplate` beans (which will be the case if you are working with multiple Keyspaces
|
||||
in the same project), then use the `@Qualifier`annotation to designate which bean you want to Autowire.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@Autowired
|
||||
@Qualifier("myTemplateBeanId")
|
||||
@Qualifier("keyspaceTwoTemplateBeanId")
|
||||
private ReactiveCassandraOperations reactiveCassandraOperations;
|
||||
----
|
||||
|
||||
@@ -453,22 +469,27 @@ You can also just lookup the `CassandraTemplate` bean from the `ApplicationConte
|
||||
ReactiveCassandraOperations reactiveCassandraOperations = applicationContext.getBean("reactiveCassandraOperations", ReactiveCassandraOperations.class);
|
||||
----
|
||||
|
||||
|
||||
[[cassandra.reactive.template.save-update-remove]]
|
||||
== Saving, Updating, and Removing Rows
|
||||
|
||||
`ReactiveCassandraTemplate` provides a simple way for you to save, update, and delete your domain objects, and map those objects
|
||||
to tables managed in Cassandra.
|
||||
`ReactiveCassandraTemplate` provides a simple way for you to save, update, and delete your domain objects,
|
||||
and map those objects to tables managed in Cassandra.
|
||||
|
||||
[[cassandra.reactive.template.insert-update]]
|
||||
=== Methods for inserting and updating rows
|
||||
|
||||
There are several convenient methods on `CassandraTemplate` for saving and inserting your objects. To have more fine-grained control over the conversion process you can register Spring converters with the `MappingCassandraConverter`, for example `Converter<Row, Person>`.
|
||||
There are several convenient methods on `CassandraTemplate` for saving and inserting your objects. To have more
|
||||
fine-grained control over the conversion process you can register Spring `Converter`s with the `MappingCassandraConverter`.
|
||||
For example, `Converter<Row, Person>`.
|
||||
|
||||
NOTE: The difference between insert and update operations is that an `INSERT` operation will not insert `null` values.
|
||||
|
||||
The simple case of using the insert operation is to save a POJO. In this case the table name will be determined by name (not fully qualified) of the class. The table to store the object can be overridden using mapping metadata.
|
||||
The simple case of using the INSERT operation is to save a POJO. In this case the table name will be determined by
|
||||
the simple class name (not fully-qualified class name). The table to store the object can be overridden
|
||||
using mapping metadata.
|
||||
|
||||
When inserting or updating, if the Id property is must be set. There are no means to generate an Id by Apache Cassandra.
|
||||
When inserting or updating, the `id` property must be set. There is no means to generate an ID in Apache Cassandra.
|
||||
|
||||
Here is a basic example of using the save operation and retrieving its contents.
|
||||
|
||||
@@ -480,25 +501,26 @@ import static org.springframework.data.cassandra.core.query.Criteria.where;
|
||||
import static org.springframework.data.cassandra.core.query.Query.query;
|
||||
…
|
||||
|
||||
Person p = new Person("Bob", 33);
|
||||
cassandraTemplate.insert(p);
|
||||
Person bob = new Person("Bob", 33);
|
||||
cassandraTemplate.insert(bob);
|
||||
|
||||
Mono<Person> qp = reactiveCassandraTemplate.selectOneById(query(where("age").is(33)), Person.class);
|
||||
Mono<Person> queriedBob = reactiveCassandraTemplate.selectOneById(query(where("age").is(33)), Person.class);
|
||||
----
|
||||
====
|
||||
|
||||
The insert/save operations available to you are listed below.
|
||||
|
||||
* `void` *insert* `(Object objectToSave)` Insert the object in an Apache Cassandra table.
|
||||
* `WriteResult` *insert* `(Object objectToSave, InsertOptions options)` Insert the object in an Apache Cassandra table applying `InsertOptions`.
|
||||
* `WriteResult` *insert* `(Object objectToSave, InsertOptions options)` Insert the object in an Apache Cassandra table
|
||||
applying `InsertOptions`.
|
||||
|
||||
A similar set of update operations is listed below
|
||||
|
||||
* `void` *update* `(Object objectToSave)` Update the object in an Apache Cassandra table.
|
||||
* `WriteResult` *update* `(Object objectToSave, UpdateOptions options)` Update the object in an Apache Cassandra table applying `UpdateOptions`.
|
||||
* `WriteResult` *update* `(Object objectToSave, UpdateOptions options)` Update the object in an Apache Cassandra table
|
||||
applying `UpdateOptions`.
|
||||
|
||||
Then, there is always the old fashioned way. You can write your own CQL statements. You can configure with `InsertOptions` and `UpdateOptions`
|
||||
additional options such as TTL, consistency level and lightweight transactions.
|
||||
Then, there is always the old fashioned way. You can write your own CQL statements.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -507,15 +529,25 @@ String cql = "insert into person (age, name) values (39, 'Bob')";
|
||||
Mono<Boolean> applied = reactiveCassandraTemplate.getReactiveCqlOperations().execute(cql);
|
||||
----
|
||||
|
||||
You can also configure additional options such as TTL, consistency level and lightweight transactions
|
||||
using `InsertOptions` and `UpdateOptions`.
|
||||
|
||||
|
||||
[[cassandra-template.insert-update.table]]
|
||||
==== Which table will my rows be inserted into?
|
||||
|
||||
There are two ways to manage the collection name that is used for operating on the tables. The default table name that is used is the class name changed to start with a lower-case letter. So a `com.test.Person` class would be stored in the "person" table. You can customize this by providing a different collection name using the `@Table` annotation.
|
||||
There are two ways to manage the collection name that is used for operating on the tables. The default table name
|
||||
used is based on the simple class name changed to start with a lower-case letter. So an instance of
|
||||
the `com.example.Person` class would be stored in in a table called "person". You can customize this by providing
|
||||
a different collection name using the `@Table` annotation.
|
||||
|
||||
[[cassandra-template.update]]
|
||||
=== Updating rows in a table
|
||||
|
||||
For updates we can select to update a number of rows. Here is an example of an update a single account object where we are adding a one-time $50.00 bonus to the balance using the `+` assignment.
|
||||
For updates, we can select to update a number of rows.
|
||||
|
||||
Here is an example of updating a single account object where we are adding a one-time $50.00 bonus to the balance
|
||||
using the `+` assignment.
|
||||
|
||||
.Updating rows using `CasandraTemplate`
|
||||
====
|
||||
@@ -532,8 +564,10 @@ Mono<Boolean> wasApplied = reactiveCassandraTemplate.update(Query.query(where("i
|
||||
----
|
||||
====
|
||||
|
||||
In addition to the `Query` discussed above we provide the update definition using an `Update` object. The `Update` class has methods that match the update assignments available for Apache Cassandra.
|
||||
In addition to the `Query` discussed above we provide the update definition using an `Update` object.
|
||||
The `Update` class has methods that match the update assignments available for Apache Cassandra.
|
||||
|
||||
As you can see most methods return the `Update` object to provide a fluent style for the API.
|
||||
As you can see most methods return the `Update` object to provide a fluent API for code styling purposes.
|
||||
|
||||
Read more about <<cassandra.template.update.methods,`Query` and `Update`>>.
|
||||
|
||||
Read more about <<cassandra.template.update.methods,`Query` and `Update`>>.
|
||||
Reference in New Issue
Block a user