DATACASS-561 - Full editing pass on reference documentation.
Original pull request: #132.
This commit is contained in:
@@ -2,8 +2,10 @@
|
||||
David Webb, Matthew Adams, John Blum, Mark Paluch, Jay Bryant
|
||||
:revnumber: {version}
|
||||
:revdate: {localdate}
|
||||
:toc:
|
||||
:toc-placement!:
|
||||
:linkcss:
|
||||
:doctype: book
|
||||
:docinfo: shared
|
||||
:toc: left
|
||||
:toclevels: 4
|
||||
:source-highlighter: prettify
|
||||
:icons: font
|
||||
|
||||
@@ -2,118 +2,106 @@
|
||||
= Preface
|
||||
|
||||
The Spring Data for Apache Cassandra project applies core Spring concepts to the development of solutions using
|
||||
the Cassandra Columnar data store. A "template" is provided as a high-level abstraction for storing
|
||||
and querying documents. You will notice similarities to the {spring-framework-docs}data-access.html#jdbc[JDBC support]
|
||||
the Cassandra Columnar data store. A "`template`" is provided as a high-level abstraction for storing
|
||||
and querying documents. This project has noticeable similarities to the {spring-framework-docs}data-access.html#jdbc[JDBC support]
|
||||
in the core Spring Framework.
|
||||
|
||||
This document is the reference guide for Spring Data support for Cassandra. It explains Cassandra module concepts,
|
||||
This document is the reference guide for Spring Data support for Cassandra. It explains Cassandra module concepts and
|
||||
semantics and the syntax for various stores namespaces.
|
||||
|
||||
This section provides a basic introduction to Spring, Spring Data and the Cassandra database. The rest of the document
|
||||
refers only to Spring Data for Apache Cassandra features and assumes the user is familiar with Cassandra as well as
|
||||
This section provides a basic introduction to Spring, Spring Data, and the Cassandra database. The rest of the document
|
||||
refers only to Spring Data for Apache Cassandra features and assumes you are familiar with Cassandra as well as
|
||||
core Spring concepts.
|
||||
|
||||
[[get-started:first-steps:spring]]
|
||||
== Knowing Spring
|
||||
|
||||
Spring Data uses the Spring Framework's {spring-framework-docs}core.html[core]
|
||||
functionality, such as the {spring-framework-docs}core.html#beans[IoC] container,
|
||||
{spring-framework-docs}core.html#validation[validation, type conversion and data binding],
|
||||
{spring-framework-docs}core.html#expressions[expression language],
|
||||
{spring-framework-docs}core.html#aop[AOP],
|
||||
{spring-framework-docs}integration.html#jmx[JMX integration],
|
||||
{spring-framework-docs}data-access.html[DAO support], and specifically
|
||||
the {spring-framework-docs}data-access.html#dao-exceptions[DAO Exception Hierarchy].
|
||||
functionality, including:
|
||||
* {spring-framework-docs}core.html#beans[IoC] container
|
||||
* {spring-framework-docs}core.html#validation[validation, type conversion and data binding]
|
||||
* {spring-framework-docs}core.html#expressions[expression language]
|
||||
* {spring-framework-docs}core.html#aop[AOP]
|
||||
* {spring-framework-docs}integration.html#jmx[JMX integration]
|
||||
* {spring-framework-docs}data-access.html[DAO support]
|
||||
* {spring-framework-docs}data-access.html#dao-exceptions[DAO Exception Hierarchy]
|
||||
|
||||
While it is not important to know the Spring APIs, understanding the concepts behind them is. At a minimum, the idea
|
||||
behind IoC should be familiar no matter what IoC container you choose to use.
|
||||
While it is not important to know the Spring APIs, understanding the concepts behind them is important. At a minimum, the idea
|
||||
behind IoC should be familiar, no matter what IoC container you choose to use.
|
||||
|
||||
The core functionality of the Cassandra support can be used directly, with no need to invoke the IoC services
|
||||
of the Spring container. This is much like `JdbcTemplate`, which can be used 'standalone' without any other services
|
||||
of the Spring container. To leverage all the features of Spring Data for Apache Cassandra, such as the repository support,
|
||||
you will need to configure some parts of the library using Spring.
|
||||
of the Spring container. To use all the features of Spring Data for Apache Cassandra, such as the repository support,
|
||||
you must configure some parts of the library by using Spring.
|
||||
|
||||
To learn more about Spring, you can refer to the comprehensive (and sometimes disarming) {spring-framework-docs}[documentation]
|
||||
that explains in detail the Spring Framework. There are a lot of articles, blog entries and books on the matter.
|
||||
Take a look at the Spring Framework http://projects.spring.io/spring-framework/[home page] for more information.
|
||||
To learn more about Spring, you can refer to the comprehensive {spring-framework-docs}[documentation]
|
||||
that explains the Spring Framework in detail. There are a lot of articles, blog entries, and books on Spring.
|
||||
See the Spring Framework http://projects.spring.io/spring-framework/[home page] for more information.
|
||||
|
||||
[[get-started:first-steps:nosql]]
|
||||
== Knowing NoSQL and Cassandra
|
||||
|
||||
NoSQL stores have taken the storage world by storm. It is a vast domain with a plethora of solutions, terms and patterns
|
||||
(to make things worse, even the term itself has multiple http://www.google.com/search?q=nosoql+acronym[meanings]).
|
||||
While some of the principles are common, it is crucial that the user is familiar to some degree with
|
||||
NoSQL stores have taken the storage world by storm. It is a vast domain with a plethora of solutions, terms, and patterns.
|
||||
(To make things worse, even the term itself has multiple http://www.google.com/search?q=nosoql+acronym[meanings].)
|
||||
While some of the principles are common, it is crucial that you be familiar to some degree with
|
||||
the Cassandra Columnar NoSQL Datastore supported by Spring Data for Apache Cassandra. The best way to get acquainted with Cassandra
|
||||
is to read the documentation and follow the examples. It usually doesn't take more then 5-10 minutes to go through them
|
||||
and if you are coming from a RDBMS background, many times these exercises can be an eye opener.
|
||||
is to read the documentation and follow the examples. It usually does not take more then 5-10 minutes to go through them,
|
||||
and, if you come from a RDBMS background, these exercises can often be an eye opener.
|
||||
|
||||
The starting ground for learning about Cassandra is http://cassandra.apache.org/[cassandra.apache.org]. Also, here is
|
||||
The starting point for learning about Cassandra is http://cassandra.apache.org/[cassandra.apache.org]. Also, here is
|
||||
a list of other useful resources:
|
||||
|
||||
* The http://datastax.com/[DataStax] site offers http://www.datastax.com/what-we-offer/products-services/support[commercial support]
|
||||
and many resources, including, but not limited to, http://docs.datastax.com/en/landing_page/doc/landing_page/current.html[documentation],
|
||||
http://docs.datastax.com/en/landing_page/doc/landing_page/current.html[DataStax Academy], a http://www.datastax.com/dev/blog[Tech Blog]
|
||||
http://docs.datastax.com/en/landing_page/doc/landing_page/current.html[DataStax Academy], a http://www.datastax.com/dev/blog[Tech Blog],
|
||||
and so on.
|
||||
* The https://academy.datastax.com/resources/ds101-introduction-cassandra[DataStax Academy introduction to cassandra]
|
||||
* The https://academy.datastax.com/resources/ds101-introduction-cassandra[DataStax Academy introduction to Cassandra].
|
||||
* The http://cassandra.apache.org/doc/latest/getting_started/index.html[Cassandra Quick Start Guide].
|
||||
|
||||
[[requirements]]
|
||||
== Requirements
|
||||
|
||||
Spring Data for Apache Cassandra 1.x binaries require JDK level 6.0 and above, and http://spring.io/docs[Spring Framework] {springVersion} and above.
|
||||
Spring Data for Apache Cassandra 1.x binaries require JDK level 6.0 and later and http://spring.io/docs[Spring Framework] {springVersion} and later.
|
||||
|
||||
In terms of http://cassandra.apache.org/[Cassandra] at least 2.0.
|
||||
It requires http://cassandra.apache.org/[Cassandra] 2.0 or later.
|
||||
|
||||
== Additional Help Resources
|
||||
|
||||
Learning a new framework is not always straight forward. In this section, we try to provide what we
|
||||
think is an easy to follow guide for starting with Spring Data for Apache Cassandra module.
|
||||
However, if you encounter issues or you are just looking for an advice, feel free to use one of the links below:
|
||||
|
||||
[[get-started:help]]
|
||||
=== Support
|
||||
|
||||
There are a few support options available:
|
||||
think is an easy-to-follow guide for starting with the Spring Data for Apache Cassandra module.
|
||||
However, if you encounter issues or you need advice, feel free to use one of the links below:
|
||||
|
||||
[[get-started:help:community]]
|
||||
==== Community Forum
|
||||
|
||||
Spring Data on http://stackoverflow.com/questions/tagged/spring-data[Stackoverflow] is a
|
||||
Community Forum::
|
||||
Spring Data on http://stackoverflow.com/questions/tagged/spring-data[Stack Overflow] is a
|
||||
tag for all Spring Data (not just Cassandra) users to share information and help each other.
|
||||
Note that registration is needed *only* for posting.
|
||||
|
||||
Developers post questions and answers on . The two key tags to search for related answers to
|
||||
this project are:
|
||||
|
||||
* http://stackoverflow.com/questions/tagged/spring-data[spring-data]
|
||||
* http://stackoverflow.com/questions/tagged/spring-data-cassandra[spring-data-cassandra]
|
||||
Note that registration is needed only for posting. The two key tags to search for related answers to
|
||||
this project are http://stackoverflow.com/questions/tagged/spring-data[spring-data] and http://stackoverflow.com/questions/tagged/spring-data-cassandra[spring-data-cassandra].
|
||||
|
||||
[[get-started:help:professional]]
|
||||
==== Professional Support
|
||||
|
||||
Professional Support::
|
||||
Professional, from-the-source support, with guaranteed response time, is available from
|
||||
http://pivotal.io/[Pivotal Sofware, Inc.], the company behind Spring Data and Spring.
|
||||
|
||||
[[get-started:up-to-date]]
|
||||
=== Following Development
|
||||
|
||||
For information on the Spring Data for Apache Cassandra source code repository, nightly builds and snapshot artifacts
|
||||
please see the http://projects.spring.io/spring-data-cassandra/[Spring Data for Apache Cassandra homepage].
|
||||
For information on the Spring Data for Apache Cassandra source code repository, nightly builds, and snapshot artifacts
|
||||
see the http://projects.spring.io/spring-data-cassandra/[Spring Data for Apache Cassandra home page].
|
||||
You can help make Spring Data best serve the needs of the Spring community by interacting with developers
|
||||
through the Community on http://stackoverflow.com/questions/tagged/spring-data[Stackoverflow].
|
||||
To follow developer activity look for the mailing list information on the Spring Data for Apache Cassandra homepage.
|
||||
through the community on http://stackoverflow.com/questions/tagged/spring-data[Stack Overflow].
|
||||
To follow developer activity, look for the mailing list information on the Spring Data for Apache Cassandra home page.
|
||||
If you encounter a bug or want to suggest an improvement, please create a ticket on the Spring Data issue
|
||||
https://jira.spring.io/browse/DATACASS[tracker]. To stay up to date with the latest news and announcements
|
||||
in the Spring eco system, subscribe to the Spring Community http://spring.io[Portal].
|
||||
Lastly, you can follow the Spring http://spring.io/blog[blog] or the project team on Twitter (http://twitter.com/SpringData[SpringData]).
|
||||
https://jira.spring.io/browse/DATACASS[tracker]. To stay up-to-date with the latest news and announcements
|
||||
in the Spring ecosystem, subscribe to the Spring Community http://spring.io[Portal].
|
||||
Finally, you can follow the Spring http://spring.io/blog[blog] or the project team on Twitter (http://twitter.com/SpringData[SpringData]).
|
||||
|
||||
|
||||
[[get-started:project-metadata]]
|
||||
=== Project Metadata
|
||||
|
||||
* Version Control - https://github.com/spring-projects/spring-data-cassandra
|
||||
* Bugtracker - https://jira.spring.io/browse/DATACASS
|
||||
* Release repository - https://repo.spring.io/libs-release
|
||||
* Milestone repository - https://repo.spring.io/libs-milestone
|
||||
* Snapshot repository - https://repo.spring.io/libs-snapshot
|
||||
|
||||
* Version Control: https://github.com/spring-projects/spring-data-cassandra
|
||||
* Bugtracker: https://jira.spring.io/browse/DATACASS
|
||||
* 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,18 +1,15 @@
|
||||
[[cassandra.repositories]]
|
||||
= Cassandra Repositories
|
||||
|
||||
[[cassandra-repo-intro]]
|
||||
== Introduction
|
||||
|
||||
This chapter covers the details of the Spring Data Repository support for Apache Cassandra.
|
||||
Cassandra's Repository support builds on the core Repository support explained in <<repositories>>.
|
||||
So make sure you understand of the basic concepts explained there before proceeding.
|
||||
Cassandra's repository support builds on the core repository support explained in "`<<repositories>>`".
|
||||
You should understand the basic concepts explained there before proceeding.
|
||||
|
||||
[[cassandra-repo-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 domain entities stored in Apache Cassandra, you can use Spring Data's sophisticated repository support,
|
||||
which significantly eases implementing DAOs. To do so, create an interface for your repository, as the following example shows:
|
||||
|
||||
.Sample Person entity
|
||||
====
|
||||
@@ -31,11 +28,13 @@ 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.
|
||||
Note that the entity has a property named `id` of type `String`.
|
||||
The default serialization mechanism used in `CassandraTemplate` (which backs the repository support)
|
||||
regards properties named `id` as being the row ID.
|
||||
|
||||
.Basic Repository interface to persist Person entities
|
||||
The following example shows a repository definition to persist `Person` entities:
|
||||
|
||||
.Basic repository interface to persist `Person` entities
|
||||
====
|
||||
[source]
|
||||
----
|
||||
@@ -46,8 +45,9 @@ public interface PersonRepository extends CrudRepository<Person, String> {
|
||||
----
|
||||
====
|
||||
|
||||
Right now this interface simply serves typing purposes, but we will add additional methods to it later.
|
||||
In your Spring configuration simply add:
|
||||
Right now, the interface in the preceding example serves only typing purposes, but we add additional methods to it later.
|
||||
|
||||
Next, in your Spring configuration, add the following (if you use XML for configuration):
|
||||
|
||||
.General Cassandra repository Spring configuration
|
||||
====
|
||||
@@ -79,16 +79,17 @@ In your Spring configuration simply add:
|
||||
----
|
||||
====
|
||||
|
||||
The `cassandra:repositories` namespace element will cause the base packages to be scanned for interfaces
|
||||
extending `CrudRepository` and create Spring beans for each one found. By default, the Repositories will be
|
||||
The `cassandra:repositories` namespace element causes the base packages to be scanned for interfaces that
|
||||
extend `CrudRepository` and create Spring beans for each one found. By default, the repositories are
|
||||
wired with a `CassandraTemplate` Spring bean called `cassandraTemplate`, so you only need to configure
|
||||
`cassandra-template-ref` explicitly if you deviate from this convention.
|
||||
|
||||
If you'd rather like to go with JavaConfig use the `@EnableCassandraRepositories` annotation. The annotation carries
|
||||
the same attributes as the namespace element. If no base package is configured the infrastructure will scan
|
||||
If you want to use Java configuration, use the `@EnableCassandraRepositories` annotation. The annotation carries
|
||||
the same attributes as the namespace element. If no base package is configured, the infrastructure scans
|
||||
the package of the annotated configuration class.
|
||||
The following example shows how to use the `@EnableCassandraRepositories` annotation:
|
||||
|
||||
.JavaConfig for repositories
|
||||
.Java configuration for repositories
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@@ -108,8 +109,9 @@ class ApplicationConfig extends AbstractCassandraConfiguration {
|
||||
----
|
||||
====
|
||||
|
||||
As our domain Repository extends `CrudRepository` it provides you with basic CRUD operations.
|
||||
Working with the Repository instance is just a matter of injecting the Repository as a dependency into a client.
|
||||
Because our domain repository extends `CrudRepository`, it provides you with basic CRUD operations.
|
||||
Working with the repository instance is a matter of injecting the repository as a dependency into a client,
|
||||
as the following example does by autowiring `PersonRepository`:
|
||||
|
||||
.Basic access to Person entities
|
||||
====
|
||||
@@ -131,9 +133,9 @@ public class PersonRepositoryTests {
|
||||
----
|
||||
====
|
||||
|
||||
Cassandra repositories support paging and sorting for paginated and sorted access to the entities. Cassandra paging requires a paging state to forward-only navigate through pages. A `Slice` keeps track of the current paging state and allows creation of a `Pageable` to request the next page.
|
||||
Cassandra repositories support paging and sorting for paginated and sorted access to the entities. Cassandra paging requires a paging state to forward-only navigate through pages. A `Slice` keeps track of the current paging state and allows for creation of a `Pageable` to request the next page. The following example shows how to set up paging access to `Person` entities:
|
||||
|
||||
.Paging access to Person entities
|
||||
.Paging access to `Person` entities
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@@ -158,17 +160,18 @@ public class PersonRepositoryTests {
|
||||
----
|
||||
====
|
||||
|
||||
NOTE: Cassandra repositories do not extend `PagingAndSortingRepository` because classic paging patterns using limit/offset are not applicable to Cassandra.
|
||||
NOTE: Cassandra repositories do not extend `PagingAndSortingRepository`, because classic paging patterns using limit/offset are not applicable to Cassandra.
|
||||
|
||||
The sample creates an application context with Spring's unit test support, which will perform annotation-based
|
||||
dependency injection into the test class. Inside the test cases (test methods) we simply use the Repository to query
|
||||
the data store. We invoke the Repository query method that requests the all `Person` instances.
|
||||
The preceding example creates an application context with Spring's unit test support, which performs annotation-based
|
||||
dependency injection into the test class. Inside the test cases (the test methods), we use the repository to query
|
||||
the data store. We invoke the repository query method that requests all `Person` instances.
|
||||
|
||||
[[cassandra.repositories.queries]]
|
||||
== Query methods
|
||||
== Query Methods
|
||||
|
||||
Most of the data access operations you usually trigger on a Repository result in a query being executed against
|
||||
the Apache Cassandra database. Defining such a query is just a matter of declaring a method on the Repository interface.
|
||||
Most of the data access operations you usually trigger on a repository result in a query being executed against
|
||||
the Apache Cassandra database. Defining such a query is a matter of declaring a method on the repository interface.
|
||||
The following example shows a number of such method declarations:
|
||||
|
||||
.PersonRepository with query methods
|
||||
====
|
||||
@@ -194,23 +197,25 @@ public interface PersonRepository extends CrudRepository<Person, String> {
|
||||
List<Person> findAllByAge(int age); <8>
|
||||
}
|
||||
----
|
||||
<1> The method shows a query for all people with the given `lastname`. The query will be derived from parsing
|
||||
the method name for constraints which can be concatenated with `And`. Thus the method name will result in
|
||||
<1> The method shows a query for all people with the given `lastname`. The query is derived from parsing
|
||||
the method name for constraints, which can be concatenated with `And`. Thus, the method name results in
|
||||
a query expression of `SELECT * from person WHERE lastname = 'lastname'`.
|
||||
<2> Applies pagination to a query. Just equip your method signature with a `Pageable` parameter and let the method return a `Slice` instance and we will automatically page the query accordingly.
|
||||
<3> Passing a `QueryOptions` object will apply the query options to the resulting query before it's execution.
|
||||
<4> Applies dynamic sorting to a query. Just add a `Sort` parameter to your method signature and Spring Data
|
||||
will automatically apply ordering to the query accordingly.
|
||||
<5> Shows that you can query based on properties which are not a primitive type using registered ``Converter``'s
|
||||
in `CustomConversions`. Throws `IncorrectResultSizeDataAccessException` if more than one match found.
|
||||
<6> Uses the `First` keyword to restrict the query to the very first result. Unlike 5, this method does
|
||||
not throw an exception if more than one match was found.
|
||||
<7> Uses a Java 8 `Stream` which reads and converts individual elements while iterating the stream.
|
||||
<8> Shows a query method annotated with `@AllowFiltering` that allows server-side filtering.
|
||||
<2> Applies pagination to a query. You can equip your method signature with a `Pageable` parameter and let the method return a `Slice` instance, and we automatically page the query accordingly.
|
||||
<3> Passing a `QueryOptions` object applies the query options to the resulting query before its execution.
|
||||
<4> Applies dynamic sorting to a query. You can add a `Sort` parameter to your method signature, and Spring Data
|
||||
automatically applies ordering to the query.
|
||||
<5> Shows that you can query based on properties that are not a primitive type by using Converter` instances registered
|
||||
in `CustomConversions`. Throws `IncorrectResultSizeDataAccessException` if more than one match is found.
|
||||
<6> Uses the `First` keyword to restrict the query to only the first result. Unlike the preceding method, this method does
|
||||
not throw an exception if more than one match is found.
|
||||
<7> Uses a Java 8 `Stream` to read and convert individual elements while iterating the stream.
|
||||
<8> Shows a query method annotated with `@AllowFiltering`, to allow server-side filtering.
|
||||
====
|
||||
|
||||
NOTE: Querying non-primary key properties requires secondary indexes.
|
||||
|
||||
The following table shows short examples of the keywords that you can use in query methods:
|
||||
|
||||
[cols="1,2,3", options="header"]
|
||||
.Supported keywords for query methods
|
||||
|===
|
||||
@@ -275,17 +280,18 @@ NOTE: Querying non-primary key properties requires secondary indexes.
|
||||
include::../{spring-data-commons-docs}/repository-projections.adoc[leveloffset=+2]
|
||||
|
||||
[[cassandra.repositories.queries.options]]
|
||||
=== Query options
|
||||
=== Query Options
|
||||
|
||||
You can specify query options for query methods by passing a `QueryOptions` object
|
||||
to apply options to the query before the actual query execution.
|
||||
`QueryOptions` is treated as non-query parameter and isn't considered as query parameter value.
|
||||
You can specify query options for query methods by passing a `QueryOptions` object.
|
||||
The options apply to the query before the actual query execution.
|
||||
`QueryOptions` is treated as a non-query parameter and is not considered to be a query parameter value.
|
||||
Query options apply to derived and string `@Query` repository methods.
|
||||
|
||||
For static declaration of a consistency level, use the `@Consistency` annotation on query methods.
|
||||
To statically set the consistency level, use the `@Consistency` annotation on query methods.
|
||||
The declared consistency level is applied to the query each time it is executed.
|
||||
The following example sets the consistency level to `ConsistencyLevel.LOCAL_ONE`:
|
||||
|
||||
Query options are applicable to derived and string `@Query` repository methods.
|
||||
|
||||
====
|
||||
----
|
||||
public interface PersonRepository extends CrudRepository<Person, String> {
|
||||
|
||||
@@ -295,23 +301,25 @@ public interface PersonRepository extends CrudRepository<Person, String> {
|
||||
List<Person> findByFirstname(String firstname, QueryOptions options);
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
NOTE: You can control fetch size, consistency level and retry policy defaults by configuring these parameters
|
||||
on the CQL API instances `CqlTemplate`, `AsyncCqlTemplate`, and `ReactiveCqlTemplate`. Defaults apply if the particular
|
||||
The DataStax Cassandra documentation includes https://docs.datastax.com/en/cassandra/3.0/cassandra/dml/dmlConfigConsistency.html[a good discussion of the available consistency levels].
|
||||
|
||||
NOTE: You can control fetch size, consistency level, and retry policy defaults by configuring the following parameters
|
||||
on the CQL API instances: `CqlTemplate`, `AsyncCqlTemplate`, and `ReactiveCqlTemplate`. Defaults apply if the particular
|
||||
query option is not set.
|
||||
|
||||
[[cassandra.repositories.misc]]
|
||||
== Miscellaneous
|
||||
|
||||
[[cassandra.repositories.misc.cdi-integration]]
|
||||
=== CDI Integration
|
||||
|
||||
Instances of the Repository interfaces are usually created by a container, and the Spring container is
|
||||
Instances of the repository interfaces are usually created by a container, and the Spring container is
|
||||
the most natural choice when working with Spring Data. Spring Data for Apache Cassandra ships with
|
||||
a custom CDI extension that allows using the repository abstraction in CDI environments. The extension
|
||||
is part of the JAR so all you need to do to activate it is dropping the Spring Data for Apache Cassandra JAR
|
||||
into your classpath. You can now set up the infrastructure by implementing a CDI Producer for the `CassandraTemplate`:
|
||||
is part of the JAR. To activate it, drop the Spring Data for Apache Cassandra JAR
|
||||
into your classpath. You can now set up the infrastructure by implementing a CDI Producer for the
|
||||
`CassandraTemplate`, as the following examlpe shows:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
class CassandraTemplateProducer {
|
||||
@@ -352,11 +360,14 @@ class CassandraTemplateProducer {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
The Spring Data for Apache Cassandra CDI extension will pick up `CassandraOperations` available as CDI bean
|
||||
and create a proxy for a Spring Data Repository whenever an bean of a Repository type is requested by the container.
|
||||
Thus obtaining an instance of a Spring Data Repository is a matter of declaring an `@Inject`-ed property:
|
||||
The Spring Data for Apache Cassandra CDI extension picks up `CassandraOperations` as a CDI bean
|
||||
and creates a proxy for a Spring Data repository whenever a bean of a repository type is requested by the container.
|
||||
Thus, obtaining an instance of a Spring Data repository is a matter of declaring an injected property,
|
||||
as the following example shows:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
class RepositoryClient {
|
||||
@@ -369,4 +380,4 @@ class RepositoryClient {
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
====
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,23 +1,25 @@
|
||||
[[cassandra.custom-converters]]
|
||||
== Overriding default mapping with 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
|
||||
`CassandraConverter` implementations, such as the `MappingCassandraConverter`.
|
||||
To have more fine-grained control over the mapping process, you can register Spring `Converters` with
|
||||
`CassandraConverter` implementations, such as `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
|
||||
`MappingCassandraConverter` first checks to see whether any Spring `Converters` 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
|
||||
need to create an implementation of the Spring `Converter` interface and register it with
|
||||
the `MappingCassandraConverter`.
|
||||
|
||||
NOTE: For more information on Spring's type conversion service, see the reference docs
|
||||
{spring-framework-docs}core.html#core-convert[here].
|
||||
|
||||
[[cassandra.custom-converters.writer]]
|
||||
=== Saving using a registered Spring Converter
|
||||
=== Saving by Using a Registered Spring Converter
|
||||
|
||||
An example implementation of a `Converter` that converts a `Person` object to a `java.lang.String`
|
||||
using Jackson 2 is shown below:
|
||||
You can combine converting and saving in a single process, basically using the converter to do the saving.
|
||||
|
||||
The following example uses a `Converter` to convert a `Person` object to a `java.lang.String`
|
||||
with Jackson 2:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -40,10 +42,12 @@ static class PersonWriteConverter implements Converter<Person, String> {
|
||||
----
|
||||
|
||||
[[cassandra.custom-converters.reader]]
|
||||
=== Reading using a Spring Converter
|
||||
=== Reading by Using a Spring Converter
|
||||
|
||||
An example implementation of a `Converter` that converts a `java.lang.String` into a `Person` object
|
||||
using Jackson 2 is shown below:
|
||||
Similar to how you can combine saving and converting, you can also combine reading and converting.
|
||||
|
||||
The following example uses a `Converter` that converts a `java.lang.String` into a `Person` object
|
||||
with Jackson 2:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -70,11 +74,11 @@ static class PersonReadConverter implements Converter<String, Person> {
|
||||
----
|
||||
|
||||
[[cassandra.custom-converters.java]]
|
||||
=== Registering Spring Converters with the CassandraConverter
|
||||
=== Registering Spring Converters with `CassandraConverter`
|
||||
|
||||
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`.
|
||||
Spring Data for Apache Cassandra Java configuration provides a convenient way to register Spring `Converter` instances:
|
||||
`MappingCassandraConverter`. The following configuration snippet shows how to manually register converters
|
||||
as well as configure `CustomConversions`:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -97,13 +101,13 @@ public static class Config extends AbstractCassandraConfiguration {
|
||||
----
|
||||
|
||||
[[cassandra.converter-disambiguation]]
|
||||
=== Converter disambiguation
|
||||
=== Converter Disambiguation
|
||||
|
||||
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.
|
||||
Depending on whether one of those is a type Cassandra can handle natively, Spring Data registers the `Converter`
|
||||
instance as a reading or a writing converter.
|
||||
|
||||
Have a look at the following samples:
|
||||
Consider the following samples:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -114,12 +118,11 @@ class MyConverter implements Converter<Person, String> { … }
|
||||
class MyConverter implements Converter<String, Person> { … }
|
||||
----
|
||||
|
||||
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`.
|
||||
If you implement a `Converter` whose source and target types are native Cassandra types,
|
||||
Spring Data cannot determine whether we should consider it as a reading or a 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`
|
||||
For example, 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 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
|
||||
for one way only, we provide `@ReadingConverter` as well as `@WritingConverter` to indicate the appropriate
|
||||
`Converter` implementation.
|
||||
|
||||
|
||||
@@ -5,8 +5,7 @@ This has traditionally been for JDBC and JPA. Spring Data for Apache Cassandra e
|
||||
by providing an implementation of the `org.springframework.dao.support.PersistenceExceptionTranslator` interface.
|
||||
|
||||
The motivation behind mapping to Spring's {spring-framework-docs}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
|
||||
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
|
||||
is to let you 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
|
||||
`DataAccessException` class, so you can be sure that you can catch all database-related exceptions
|
||||
within a single try-catch block.
|
||||
|
||||
|
||||
@@ -6,15 +6,15 @@ This part of the reference documentation explains the core functionality offered
|
||||
|
||||
<<cassandra.reactive>> explains reactive Cassandra specifics.
|
||||
|
||||
<<cassandra.repositories>> introduces _Repository_ support for Cassandra.
|
||||
<<cassandra.repositories>> introduces repository support for Cassandra.
|
||||
|
||||
[[cassandra.modules]]
|
||||
== Spring CQL and Spring Data for Apache Cassandra modules
|
||||
== Spring CQL and Spring Data for Apache Cassandra Modules
|
||||
|
||||
Spring Data for Apache Cassandra allows interaction on both the CQL as well as the entity-level.
|
||||
Spring Data for Apache Cassandra allows interaction on both the CQL and the entity level.
|
||||
|
||||
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
|
||||
The value 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 which actions Spring take care of
|
||||
and which actions are the responsibility of you, the application developer.
|
||||
|
||||
[[cassandra.modules.who-does-what]]
|
||||
@@ -38,7 +38,7 @@ and which actions are the responsibility of you, the application developer.
|
||||
|
|
||||
| X
|
||||
|
||||
| Prepare and execute the statement.
|
||||
| Prepare and run the statement.
|
||||
| X
|
||||
|
|
||||
|
||||
@@ -60,25 +60,24 @@ and which actions are the responsibility of you, the application developer.
|
||||
|===
|
||||
|
||||
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.
|
||||
with which to develop. Using mapped entity objects allows schema generation, object mapping, and repository support.
|
||||
|
||||
[[cassandra.choose-style]]
|
||||
=== Choosing an approach for Cassandra database access
|
||||
=== Choosing an Approach for Cassandra Database Access
|
||||
|
||||
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.
|
||||
and match to include a feature from a different approach. The following approaches work well:
|
||||
|
||||
* <<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`
|
||||
* <<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. Note that 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
|
||||
* <<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.
|
||||
* <<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
|
||||
* Repository Abstraction lets you 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.
|
||||
|
||||
|
||||
@@ -4,23 +4,23 @@
|
||||
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.
|
||||
The mapping metadata model is populated by using annotations on your domain objects. However, the infrastructure
|
||||
is not limited to using annotations as the only source of metadata. The `MappingCassandraConverter` also lets you
|
||||
map domain objects to tables without providing any additional metadata, by following a set of conventions.
|
||||
|
||||
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.
|
||||
In this chapter, we 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-conversion]]
|
||||
== Data Mapping and Type Conversion
|
||||
|
||||
This section explains how types are mapped to an Apache Cassandra representation and vice versa.
|
||||
This section explains how types are mapped to and from an Apache Cassandra representation.
|
||||
|
||||
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 custom converters to adjust type conversion, see <<cassandra.mapping.explicit-converters>>
|
||||
for further details.
|
||||
You can provide your own custom converters to adjust type conversion. See "`<<cassandra.mapping.explicit-converters>>`"
|
||||
for further details. The following table maps Spring Data types to Cassandra types:
|
||||
|
||||
[cols="3,2", options="header"]
|
||||
.Type
|
||||
@@ -103,9 +103,9 @@ for further details.
|
||||
|
||||
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`.
|
||||
Java types can be mapped to other Cassandra types by using `@CassandraType`, as the following example shows:
|
||||
|
||||
.Enum Mapping to Numeric Types
|
||||
.Enum mapping to numeric types
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@@ -123,8 +123,8 @@ public enum Condition {
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
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]]
|
||||
@@ -133,9 +133,9 @@ NOTE: `Enum` mapping using ordinal values requires at least Spring 4.3.0. Using
|
||||
`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
|
||||
* The simple (short) Java class name is mapped to the table name by being changed to lower case.
|
||||
For example, `com.bigbank.SavingsAccount` maps to a table named `savingsaccount`.
|
||||
* The converter uses any registered Spring `Converter` instances 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.
|
||||
|
||||
@@ -144,11 +144,11 @@ tables fields.
|
||||
=== Mapping Configuration
|
||||
|
||||
Unless explicitly configured, an instance of `MappingCassandraConverter` is created by default when creating
|
||||
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.
|
||||
a `CassandraTemplate`. You can create your own instance of the `MappingCassandraConverter` to tell it
|
||||
where to scan the classpath at startup for your domain classes to extract metadata and construct indexes.
|
||||
|
||||
Also, by creating your own instance you can register Spring `Converter`s to use for mapping specific classes
|
||||
to and from the database.
|
||||
Also, by creating your own instance, you can register Spring `Converter` instances to use for mapping specific classes
|
||||
to and from the database. The following example configuration class sets up Cassandra mapping support:
|
||||
|
||||
.@Configuration class to configure Cassandra mapping support
|
||||
====
|
||||
@@ -185,24 +185,24 @@ public static class Config extends AbstractCassandraConfiguration {
|
||||
----
|
||||
====
|
||||
|
||||
`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.
|
||||
`AbstractCassandraConfiguration` requires you to implement methods that define a keyspace.
|
||||
`AbstractCassandraConfiguration` also has a method named `getEntityBasePackages(…)`. You can override it
|
||||
to tell the converter where to scan for classes annotated with the `@Table` annotation.
|
||||
|
||||
You can add additional converters to the `MappingCassandraConverter` by overriding the method `customConversions`.
|
||||
You can add additional converters to the `MappingCassandraConverter` by overriding the `customConversions` method.
|
||||
|
||||
NOTE: `AbstractCassandraConfiguration` will create a `CassandraTemplate` instance and register it with the container
|
||||
under the name `cassandraTemplate`.
|
||||
NOTE: `AbstractCassandraConfiguration` creates a `CassandraTemplate` instance and registers it with the container
|
||||
under the name of `cassandraTemplate`.
|
||||
|
||||
|
||||
[[mapping.usage]]
|
||||
== 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 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 lose your data.
|
||||
you should annotate your mapped domain objects with the `@Table` annotation. Doing so lets the classpath scanner find
|
||||
and pre-process your domain objects to extract the necessary metadata. Only annotated entities are used
|
||||
to perform schema actions. In the worst case, a `SchemaAction.RECREATE_DROP_UNUSED` operation drops your tables
|
||||
and you lose your data. The following example shows a simple domain object:
|
||||
|
||||
.Example domain object
|
||||
====
|
||||
@@ -235,16 +235,17 @@ Composite primary keys can require a slightly different data model.
|
||||
|
||||
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
|
||||
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.
|
||||
|
||||
Primary keys can make use of any singular simple Cassandra type or mapped User-Defined Type.
|
||||
Primary keys can make use of any singular simple Cassandra type or mapped user-defined Type.
|
||||
Collection-typed primary keys are not supported.
|
||||
|
||||
==== Simple Primary Key
|
||||
==== Simple Primary Keys
|
||||
|
||||
A simple primary key consists of one partition key field within an entity class. Since it's one field only,
|
||||
we safely can assume it's a partition key.
|
||||
A simple primary key consists of one partition key field within an entity class. Since it is one field only,
|
||||
we safely can assume it is a partition key.
|
||||
The following listing shows a CQL table defined in Cassandra with a primary key of `user_id`:
|
||||
|
||||
.CQL Table defined in Cassandra
|
||||
====
|
||||
@@ -259,6 +260,8 @@ CREATE TABLE user (
|
||||
----
|
||||
====
|
||||
|
||||
The following example shows a Java class annotated such that it corresponds to the Cassandra defined in the previous listing:
|
||||
|
||||
.Annotated Entity
|
||||
====
|
||||
[source,java]
|
||||
@@ -278,19 +281,20 @@ public class LoginEvent {
|
||||
----
|
||||
====
|
||||
|
||||
==== Composite Key
|
||||
==== Composite Keys
|
||||
|
||||
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:
|
||||
|
||||
1. Embedded in an entity.
|
||||
2. By using `@PrimaryKeyClass`.
|
||||
* Embedded in an entity.
|
||||
* By using `@PrimaryKeyClass`.
|
||||
|
||||
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.
|
||||
The following example shows a CQL table and the corresponding POJOs that represent the table and its composite key:
|
||||
// TODO Add the POJOs
|
||||
|
||||
.CQL Table with a Composite Primary Key
|
||||
====
|
||||
@@ -307,13 +311,14 @@ CREATE TABLE login_event(
|
||||
----
|
||||
====
|
||||
|
||||
==== Flat Composite Primary Key
|
||||
==== Flat Composite Primary Keys
|
||||
|
||||
Flat composite primary keys are embedded inside the entity as flat fields. Primary key fields are annotated with
|
||||
`@PrimaryKeyColumn` along with other fields in the entity. Selection requires either a query to contain predicates
|
||||
`@PrimaryKeyColumn`. Selection requires either a query to contain predicates
|
||||
for the individual fields or the use of `MapId`.
|
||||
The following example shows a class with a flat composite primary key:
|
||||
|
||||
.Using a flat Composite Primary Key
|
||||
.Using a flat composite primary key
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@@ -340,12 +345,12 @@ public class LoginEvent {
|
||||
==== Primary Key Class
|
||||
|
||||
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
|
||||
It is annotated with `@PrimaryKeyClass` and must define `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
|
||||
in a single complex object.
|
||||
Primary key classes can be used with repositories (as the `Id` type) and to represent an entity's identity
|
||||
in a single complex object. The following example shows a composite primary key class:
|
||||
|
||||
.Composite Primary Key Class
|
||||
.Composite primary key class
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@@ -366,7 +371,9 @@ public class LoginEventKey implements Serializable {
|
||||
----
|
||||
====
|
||||
|
||||
.Using a Composite Primary Key
|
||||
The following example shows how to use a composite primary key:
|
||||
|
||||
.Using a composite primary key
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@@ -388,35 +395,35 @@ NOTE: `PrimaryKeyClass` must implement `Serializable` and should provide impleme
|
||||
|
||||
|
||||
[[mapping.usage-annotations]]
|
||||
=== Mapping annotation overview
|
||||
=== Mapping Annotation Overview
|
||||
|
||||
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:
|
||||
An overview of the annotations follows:
|
||||
|
||||
* `@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.
|
||||
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
|
||||
* `@Id`: Applied at the field or property level to mark the property used for identity purposes.
|
||||
* `@Table`: Applied at the class level to indicate that this class is a candidate for mapping to the database.
|
||||
You can specify the name of the table where the object is stored.
|
||||
* `@PrimaryKey`: Similar to `@Id` but lets you specify the column name.
|
||||
* `@PrimaryKeyColumn`: Cassandra-specific annotation for primary key columns that lets you specify
|
||||
primary key column attributes, such as for clustered or partitioned. Can be used on single and multiple attributes
|
||||
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
|
||||
* `@PrimaryKeyClass`: Applied at the class level to indicate that this class is a compound primary key class.
|
||||
Must 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.
|
||||
* `@Column`: Applied at the field level. Describes the column name as it is represented in the Cassandra table,
|
||||
thus letting the name differ from 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).
|
||||
* `@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 both
|
||||
technology and data store agnostic.
|
||||
technology- and data store-agnostic.
|
||||
|
||||
Here is an example of a more complex mapping.
|
||||
The following example shows a more complex mapping:
|
||||
|
||||
.Mapped `Person` class
|
||||
====
|
||||
@@ -485,7 +492,9 @@ public class Person {
|
||||
----
|
||||
====
|
||||
|
||||
.Mapped User-Defined type `Address`
|
||||
The following example shows how to map a UDT `Address`:
|
||||
|
||||
.Mapped User-Defined Type `Address`
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@@ -507,20 +516,20 @@ public class Address {
|
||||
----
|
||||
====
|
||||
|
||||
NOTE: Working with User-Defined Types requires a `UserTypeResolver` configured with the mapping context.
|
||||
NOTE: Working with User-Defined Types requires a `UserTypeResolver` that is configured with the mapping context.
|
||||
See the <<cassandra.connectors,configuration chapter>> for how to configure a `UserTypeResolver`.
|
||||
|
||||
==== Index creation
|
||||
|
||||
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,
|
||||
You can annotate particular entity properties with `@Indexed` or `@SASI` if you wish to create secondary indexes
|
||||
on application startup. Index creation creates simple secondary indexes for scalar types, user-defined types,
|
||||
and collection types.
|
||||
|
||||
You can configure a SASI Index to apply an analyzer such as `StandardAnalyzer` or `NonTokenizingAnalyzer` via
|
||||
`@StandardAnalyzed` respective `@NonTokenizingAnalyzed`.
|
||||
You can configure a SASI Index to apply an analyzer, such as `StandardAnalyzer` or `NonTokenizingAnalyzer` (by using
|
||||
`@StandardAnalyzed` and `@NonTokenizingAnalyzed`, respectively).
|
||||
|
||||
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. The following example shows a number of ways to create an index:
|
||||
|
||||
.Variants of map indexing
|
||||
====
|
||||
@@ -547,24 +556,24 @@ public class Person {
|
||||
----
|
||||
====
|
||||
|
||||
WARNING: Index creation on session initialization may have a severe performance impact on application startup.
|
||||
CAUTION: Index creation on session initialization may have a severe performance impact on application startup.
|
||||
|
||||
|
||||
[[cassandra.mapping.explicit-converters]]
|
||||
=== Overriding Mapping with 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.
|
||||
When storing and querying objects, it is often 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 let you selectively handle the conversion for a particular type. Other times, you may want to optimize performance.
|
||||
|
||||
To selectively handle the conversion yourself, register one or more `org.springframework.core.convert.converter.Converter`
|
||||
instances with the `CassandraConverter`.
|
||||
instances with `CassandraConverter`.
|
||||
|
||||
NOTE: Spring 3.0 introduced a `o.s.core.convert` package that provides a general type conversion system.
|
||||
This is described in detail in the Spring reference documentation section entitled
|
||||
{spring-framework-docs}core.html#core-convert[Spring Type Conversion].
|
||||
This system is described in detail in the Spring reference documentation section titled
|
||||
{spring-framework-docs}core.html#core-convert[`Spring Type Conversion`].
|
||||
|
||||
Below is an example of a Spring `Converter` implementation that converts from a Row to a Person POJO.
|
||||
The following example of a Spring `Converter` implementation converts from a row to a `Person` POJO:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
|
||||
@@ -11,7 +11,7 @@ into dedicated interfaces and templates.
|
||||
* 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 CQL specifications to value objects and configurators.
|
||||
* Refactored `QueryOptions` to be immutable objects.
|
||||
* Refactored `CassandraPersistentProperty` to single-column.
|
||||
|
||||
@@ -22,15 +22,17 @@ DataStax `ConsistencyLevel` and `RetryPolicy` types.
|
||||
* 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 `CqlIdentifier.cqlId(…)` and `KeyspaceIdentifier.ksId(…)` in favor of the `.of(…)` methods.
|
||||
* Deprecated constructors of `QueryOptions` in favor of their builders.
|
||||
* Deprecated `TypedIdCassandraRepository` in favor of `CassandraRepository`
|
||||
|
||||
== Merged Spring CQL and Spring Data Cassandra modules
|
||||
== 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`.
|
||||
is no longer available. You can find all types merged into `spring-data-cassandra`.
|
||||
The following listing shows how to include `spring-data-cassandra` in your maven dependencies:
|
||||
|
||||
====
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
<dependencies>
|
||||
@@ -43,71 +45,75 @@ is no longer available. Find all types merged into `spring-data-cassandra`.
|
||||
|
||||
</dependencies>
|
||||
----
|
||||
====
|
||||
|
||||
With the merge, we merged all CQL packages into Spring Data Cassandra:
|
||||
|
||||
* Moved `o.s.d.cql` into `o.s.d.cassandra.core.cql`.
|
||||
* Merged `o.s.d.cql` with `o.s.d.cassandra.config` and flattened XML and Java subpackages.
|
||||
* Merged `o.s.d.cql` with `o.s.d.cassandra.config` and flattened the 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)
|
||||
* Moved `o.s.d.c.mapping` to `o.s.d.c.core.mapping` (affects mapping annotations)
|
||||
* 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).
|
||||
* Moved `o.s.d.c.mapping` to `o.s.d.c.core.mapping` (affects mapping annotations).
|
||||
* Moved `MapId` from `o.s.d.c.repository` to `o.s.d.c.core.mapping`.
|
||||
|
||||
== Revised `CqlTemplate`/`CassandraTemplate`
|
||||
|
||||
We split `CqlTemplate` and `CassandraTemplate` in two ways:
|
||||
We split `CqlTemplate` and `CassandraTemplate` in three ways:
|
||||
|
||||
* `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` is no longer a `CqlTemplate` but uses an instance that allows reuse and fine-grained control
|
||||
over fetch size, consistency levels, and retry policies. You can obtain the `CqlOperations` through
|
||||
`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
|
||||
* `CqlTemplate` now reflects basic CQL operations instead of mixing high-level and low-level API calls (such as `count(…)`
|
||||
versus `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`.
|
||||
|
||||
== Removed 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, as the following example shows:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
cassandraTemplate.select(Query.query(Criteria.where("id").in(…)), Person.class)
|
||||
----
|
||||
====
|
||||
|
||||
== Better names for CassandraRepository
|
||||
== Better names for `CassandraRepository`
|
||||
|
||||
We renamed `CassandraRepository` and `TypedIdCassandraRepository` to align SD Cassandra naming with other
|
||||
We renamed `CassandraRepository` and `TypedIdCassandraRepository` to align Spring Data Cassandra naming with other
|
||||
Spring Data modules:
|
||||
|
||||
* Renamed `CassandraRepository` to `MapIdCassandraRepository`
|
||||
* Renamed `TypedIdCassandraRepository` to `CassandraRepository`
|
||||
* Introduced `TypedIdCassandraRepository` extending `CassandraRepository` as deprecated type to ease migration
|
||||
* Introduced `TypedIdCassandraRepository`, extending `CassandraRepository` as a deprecated type to ease migration
|
||||
|
||||
== Removed SD Cassandra `ConsistencyLevel` and `RetryPolicy` types in favor of DataStax `ConsistencyLevel` and `RetryPolicy` types
|
||||
|
||||
SD Cassandra `ConsistencyLevel` and `RetryPolicy` have been removed. Please use the types provided by
|
||||
the DataStax driver directly.
|
||||
Spring Data Cassandra `ConsistencyLevel` and `RetryPolicy` have been removed. Please use the types provided by
|
||||
the DataStax driver.
|
||||
|
||||
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.
|
||||
The Spring Data Cassandra types restricted usage of available features provided in and allowed by the Cassandra native driver.
|
||||
As a result, the Spring Data Cassandra's types required an update each time newer functionality was introduced by the driver.
|
||||
|
||||
== Refactored CQL specifications to value objects/configurators
|
||||
== Refactored CQL Specifications to Value Objects and Configurators
|
||||
|
||||
CQL specification types are now value types as much as possible (such as `FieldSpecification`, `AlterColumnSpecification`)
|
||||
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
|
||||
As much as possible, CQL specification types are now value types (such as `FieldSpecification`, `AlterColumnSpecification`),
|
||||
and objects are constructed by static factory methods. This allows immutability for simple value objects.
|
||||
Configurator objects (such as `AlterTableSpecification`) that operate on mandatory properties (such as a table name or
|
||||
keyspace name) are initially constructed through a a static factory method and allow further configuration until
|
||||
the desired state is created.
|
||||
|
||||
== Refactored `QueryOptions` to be 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` enforce non-null objects, which are available from static `empty()` factory methods.
|
||||
The following example shows how to use `QueryOptions.builder()`:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@@ -120,11 +126,10 @@ QueryOptions queryOptions = QueryOptions.builder()
|
||||
.build();
|
||||
----
|
||||
|
||||
== Refactored `CassandraPersistentProperty` to single-column
|
||||
== Refactored `CassandraPersistentProperty` to Single-column
|
||||
|
||||
You are only affected by this change if you operate on the mapping model directly.
|
||||
This change affects You only if you operate directly on the mapping model.
|
||||
|
||||
`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. Resolved composite primary keys
|
||||
mapped to a class via `MappingContext.getRequiredPersistentEntity(…)`.
|
||||
|
||||
map to a class through `MappingContext.getRequiredPersistentEntity(…)`.
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
= Appendix E: Migration Guides
|
||||
|
||||
:leveloffset: +1
|
||||
include::migration-guide-1.5-to-2.0.adoc[]
|
||||
:leveloffset: -1
|
||||
include::migration-guide-1.5-to-2.0.adoc[leveloffset=+1]
|
||||
|
||||
@@ -1,21 +1,17 @@
|
||||
[[cassandra.reactive.repositories]]
|
||||
= Reactive Cassandra Repositories
|
||||
|
||||
|
||||
[[cassandra.reactive.repositories.intro]]
|
||||
== Introduction
|
||||
|
||||
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.
|
||||
This chapter outlines the specialties handled by the reactive repository support for Apache Cassandra.
|
||||
It builds on the core repository infrastructure explained in <<cassandra.repositories>>, so
|
||||
you should 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,
|
||||
Calling repository methods lets you compose a reactive sequence by obtaining `Publisher` instances and applying operators.
|
||||
No I/O happens until you subscribe. Passing the reactive sequence to a reactive execution infrastructure,
|
||||
such as {spring-framework-docs}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.
|
||||
or http://vertx.io/docs/vertx-reactive-streams/java/[Vert.x]), subscribes to the publisher and initiate
|
||||
the actual execution. See http://projectreactor.io/docs/core/release/reference/#reactive.subscribe[the Project reactor documentation] for more detail.
|
||||
|
||||
|
||||
[[cassandra.reactive.repositories.libraries]]
|
||||
@@ -26,14 +22,14 @@ https://github.com/ReactiveX/RxJava[RxJava] and https://projectreactor.io/[Proje
|
||||
|
||||
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.
|
||||
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)
|
||||
Project Reactor offers various adapters to convert reactive wrapper types (`Flux` to `Observable` and back),
|
||||
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 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:
|
||||
Spring Data's repository abstraction is a dynamic API that is mostly defined by you and your requirements
|
||||
as you declare query methods. Reactive Cassandra repositories can be implemented by using either RxJava
|
||||
or Project Reactor wrapper types by extending from one of the library-specific repository interfaces:
|
||||
|
||||
* `ReactiveCrudRepository`
|
||||
* `ReactiveSortingRepository`
|
||||
@@ -46,8 +42,8 @@ Spring Data converts reactive wrapper types behind the scenes so that you can st
|
||||
[[cassandra.reactive.repositories.usage]]
|
||||
== Usage
|
||||
|
||||
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_:
|
||||
To access entities stored in Apache Cassandra, you can use Spring Data's sophisticated repository support,
|
||||
which significantly eases implementing DAOs. To do so, create an interface for your repository, as the following example shows:
|
||||
|
||||
.Sample Person entity
|
||||
====
|
||||
@@ -66,9 +62,11 @@ 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 the row id.
|
||||
Note that the entity has a property named `id` of type `String`.
|
||||
The default serialization mechanism used in `CassandraTemplate` (which backs the repository support)
|
||||
regards properties named `id` as the row ID.
|
||||
|
||||
The following example interface definition includes method definitions that define queries:
|
||||
|
||||
.Basic repository interface to persist Person entities
|
||||
====
|
||||
@@ -88,18 +86,18 @@ public interface ReactivePersonRepository extends ReactiveSortingRepository<Pers
|
||||
Flux<Person> findByAge(int age); <5>
|
||||
}
|
||||
----
|
||||
<1> The method shows a query for all people with the given firstname. The query will be derived parsing the method name for constraints which can be concatenated with And and Or. Thus the method name will result in a query expression of `SELECT * FROM person WHERE firstname = :firstname`.
|
||||
<2> The method shows a query for all people with the given firstname once the firstname is emitted via the given `Publisher`.
|
||||
<3> Find a single entity for given criteria. Completes with `IncorrectResultSizeDataAccessException` on non unique results.
|
||||
<4> Unlike 3, the first entity is always emitted even if the query yields more result rows.
|
||||
<5> Shows a query method annotated with `@AllowFiltering` that allows server-side filtering.
|
||||
<1> A query for all people with the given `firstname`. The query is derived by parsing the method name for constraints, which can be concatenated with `And` and `Or`. Thus, the method name results in a query expression of `SELECT * FROM person WHERE firstname = :firstname`.
|
||||
<2> A query for all people with the given `firstname` once the `firstname` is emitted from the given `Publisher`.
|
||||
<3> Find a single entity for the given criteria. Completes with `IncorrectResultSizeDataAccessException` on non-unique results.
|
||||
<4> Unlike the preceding query, the first entity is always emitted even if the query yields more result rows.
|
||||
<5> A query method annotated with `@AllowFiltering`, which allows server-side filtering.
|
||||
====
|
||||
|
||||
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.
|
||||
For Java configuration, use the `@EnableReactiveCassandraRepositories` annotation. The annotation carries the same attributes
|
||||
as the corresponding XML namespace element. If no base package is configured, the infrastructure scans the package
|
||||
of the annotated configuration class. The following example uses the `@EnableReactiveCassandraRepositories` annotation:
|
||||
|
||||
.JavaConfig for repositories
|
||||
.Java configuration for repositories
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@@ -119,9 +117,9 @@ class ApplicationConfig extends AbstractReactiveCassandraConfiguration {
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
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 a matter of
|
||||
dependency injecting it into a client, as the following example shows:
|
||||
|
||||
.Sorted access to Person entities
|
||||
====
|
||||
@@ -143,11 +141,11 @@ public class PersonRepositoryTests {
|
||||
== Features
|
||||
|
||||
Spring Data's Reactive Cassandra support comes with the same set of features as
|
||||
<<cassandra.repositories,imperative repositories>>.
|
||||
the support for <<cassandra.repositories,imperative repositories>>.
|
||||
|
||||
The following features are supported:
|
||||
It supports the following features:
|
||||
|
||||
* Query Methods using <<cassandra.repositories.queries,String queries and Query Derivation>>
|
||||
* Query Methods that use <<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.
|
||||
NOTE: Query methods must return a reactive type. Resolved types (`User` versus `Mono<User>`) are not supported.
|
||||
|
||||
@@ -1,43 +1,43 @@
|
||||
[[cassandra.reactive]]
|
||||
= Reactive Cassandra support
|
||||
= Reactive Cassandra Support
|
||||
|
||||
The reactive Cassandra support contains a wide range of features which are summarized below.
|
||||
The reactive Cassandra support contains a wide range of features:
|
||||
|
||||
* 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.
|
||||
* `ReactiveCqlTemplate` helper class that increases productivity by properly handling common Cassandra data access operations.
|
||||
* `ReactiveCassandraTemplate` helper class that increases productivity by using `ReactiveCassandraOperations in a reactive manner. It includes integrated object mapping between tables and POJOs.
|
||||
* Exception translation into Spring's portable {spring-framework-docs}data-access.html#dao-exceptions[Data Access Exception Hierarchy].
|
||||
* Feature rich object mapping integrated with Spring's {spring-framework-docs}core.html#core-convert[Conversion Service].
|
||||
* Java-based Query, Criteria, and Update DSLs.
|
||||
* Automatic implementation of `Repository` interfaces including support for custom finder methods.
|
||||
* 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
|
||||
For most data-oriented tasks, you can use the `ReactiveCassandraTemplate` or the repository support, which use
|
||||
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.
|
||||
CRUD operations. `ReactiveCqlTemplate` also provides callback methods that make it easy to get low-level
|
||||
API objects, such as `com.datastax.driver.core.Session`, which let you 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
|
||||
in the DataStax Java Driver so that they are immediately familiar and so that you can map your existing knowledge
|
||||
onto the Spring APIs.
|
||||
|
||||
|
||||
[[cassandra.reactive.getting-started]]
|
||||
== Getting Started
|
||||
|
||||
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
|
||||
Spring Data for Apache Cassandra support requires Apache Cassandra 2.1 or later, Datastax Java Driver 3.0 or later,
|
||||
and Java SE 8 or later. An easy way to set up 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
|
||||
First, you need to set up a running Apache Cassandra server. See 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`
|
||||
for an explanation on how to start 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
|
||||
and press Yes when prompted. Then enter a project and a package name such as `org.spring.data.cassandra.example`.
|
||||
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 dependency to your pom.xml `dependencies` section, as follows:
|
||||
|
||||
====
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
<dependencies>
|
||||
@@ -50,17 +50,21 @@ Then add dependency or your _pom.xml `dependencies` section.
|
||||
|
||||
</dependencies>
|
||||
----
|
||||
====
|
||||
|
||||
Also change the version of Spring in the _pom.xml_ to be
|
||||
You should also change the version of Spring in the pom.xml to be as follows:
|
||||
|
||||
====
|
||||
[source,xml,subs="verbatim,attributes"]
|
||||
----
|
||||
<spring.framework.version>{springVersion}</spring.framework.version>
|
||||
----
|
||||
====
|
||||
|
||||
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.
|
||||
If you use a milestone release instead of a GA release, you 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), as follows:
|
||||
|
||||
====
|
||||
[source,xml]
|
||||
----
|
||||
<repositories>
|
||||
@@ -71,15 +75,17 @@ repository for Maven to your _pom.xml_, which is at the same level of your `<dep
|
||||
</repository>
|
||||
</repositories>
|
||||
----
|
||||
====
|
||||
|
||||
The repository is also http://repo.spring.io/milestone/org/springframework/data/[browseable here].
|
||||
You can browse the repository is also http://repo.spring.io/milestone/org/springframework/data/[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, you can create a simple Java application that stores and reads a domain object to and from Cassandra.
|
||||
|
||||
First, create a simple domain object class to persist.
|
||||
To do so, create a simple domain object class to persist, as the following example shows:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
package org.spring.data.cassandra.example;
|
||||
@@ -121,9 +127,11 @@ public class Person {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
Next, create the main application to run.
|
||||
Next, create the main application to run, as the following example shows:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
package org.spring.data.cassandra.example;
|
||||
@@ -173,13 +181,14 @@ public class CassandraApplication {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
Even in this simple example, there are a few things to observe.
|
||||
This simple example contains a few noteworthy items:
|
||||
|
||||
* A fully synchronous flow does not benefit from a reactive infrastructure as a reactive programming model
|
||||
* A fully synchronous flow does not benefit from a reactive infrastructure, because 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`.
|
||||
* You can create an instance of `ReactiveCassandraTemplate` with a Cassandra `Session` obtained from `Cluster`.
|
||||
* You must annotate your POJO as a Cassandra `@Table` and 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.
|
||||
|
||||
@@ -187,18 +196,18 @@ Optionally, you can override these mapping names to match your Cassandra databas
|
||||
[[cassandra.reactive.examples-repo]]
|
||||
== Examples Repository
|
||||
|
||||
There is a https://github.com/spring-projects/spring-data-examples[Github repository with several examples] that you
|
||||
A https://github.com/spring-projects/spring-data-examples[Github repository] contains several examples that you
|
||||
can download and play around with to get a feel for how the library works.
|
||||
|
||||
|
||||
[[cassandra.reactive.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 container. There are two main ways to do this, either using Java-based bean metadata or XML-based
|
||||
One of the first tasks when using Apache Cassandra and Spring is to create a `com.datastax.driver.core.Session` object by
|
||||
using the Spring container. There are two main ways to do this: either by using Java-based bean metadata or by using 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
|
||||
NOTE: For those not familiar with how to configure the Spring container by using Java-based bean metadata instead of
|
||||
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 {spring-framework-docs}core.html#beans-java-instantiating-container[here].
|
||||
@@ -207,14 +216,14 @@ as well as the detailed documentation {spring-framework-docs}core.html#beans-jav
|
||||
[[cassandra.cassandra-reactive-java-config]]
|
||||
=== Registering a Session instance using Java-based metadata
|
||||
|
||||
You can configure Reactive Cassandra support via <<cassandra.cassandra-java-config,Java Configuration classes>>.
|
||||
You can configure Reactive Cassandra support by using <<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.
|
||||
|
||||
A reactive `Session` is configured similar to an imperative `Session`. We provide supporting configuration classes
|
||||
A reactive `Session` is configured similarly 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 the reactive support will also configure
|
||||
the imperative API support as well.
|
||||
class extends the imperative `AbstractCassandraConfiguration`, so the reactive support also configures
|
||||
the imperative API support. The following example shows how to register Apache Cassandra beans in a configuration class:
|
||||
|
||||
.Registering Spring Data for Apache Cassandra beans using `AbstractReactiveCassandraConfiguration`
|
||||
====
|
||||
@@ -240,68 +249,75 @@ public class AppConfig extends AbstractReactiveCassandraConfiguration {
|
||||
----
|
||||
====
|
||||
|
||||
This configuration class is schema-management-enabled to create CQL objects during startup.
|
||||
The configuration class in the preceding example is schema-management-enabled to create CQL objects during startup.
|
||||
See <<cassandra.schema-management>> for further details.
|
||||
|
||||
|
||||
[[cassandra.reactive.cql-template]]
|
||||
== ReactiveCqlTemplate
|
||||
== `ReactiveCqlTemplate`
|
||||
|
||||
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,
|
||||
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.
|
||||
and update statements and performs iteration over `ResultSet` instances 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` 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`
|
||||
When you use the `ReactiveCqlTemplate` in your code, you need only implement callback interfaces, which have a
|
||||
clearly defined contract. Given a `Connection`, the `ReactivePreparedStatementCreator` 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 `ReactiveResultSet`.
|
||||
|
||||
The `ReactiveCqlTemplate` can be used within a DAO implementation through direct instantiation with a `ReactiveSessionFactory`
|
||||
reference, or be configured in the Spring container and given to DAOs as a bean reference. `ReactiveCqlTemplate` is
|
||||
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
|
||||
class name of the template instance (typically `ReactiveCqlTemplate`, but it may be different if you use
|
||||
a custom subclass of the `ReactiveCqlTemplate` class).
|
||||
|
||||
|
||||
[[cassandra.reactive.cql-template.examples]]
|
||||
=== Examples of `ReactiveCqlTemplate` class usage
|
||||
=== 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.
|
||||
of all of the functionality exposed by the `ReactiveCqlTemplate`. See the attendant https://docs.spring.io/spring-data/cassandra/docs/current/api/index.html?org/springframework/cassandra/core/ReactiveCqlTemplate.html[Javadocs] for that.
|
||||
|
||||
[[cql-template.examples.query]]
|
||||
==== Querying (SELECT) with `ReactiveCqlTemplate`
|
||||
Here is a simple query for getting the number of rows in a relation:
|
||||
The following query gets the number of rows in a relation:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
Mono<Integer> rowCount = reactiveCqlTemplate.queryForObject("select count(*) from t_actor", Integer.class);
|
||||
----
|
||||
====
|
||||
|
||||
A simple query using a bind variable:
|
||||
The following query uses a bind variable:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
Mono<Integer> countOfActorsNamedJoe = reactiveCqlTemplate.queryForObject(
|
||||
"select count(*) from t_actor where first_name = ?", Integer.class, "Joe");
|
||||
----
|
||||
====
|
||||
|
||||
Querying for a `String`:
|
||||
The following example queries for a `String`:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
Mono<String> lastName = reactiveCqlTemplate.queryForObject(
|
||||
"select last_name from t_actor where id = ?",
|
||||
String.class, 1212L);
|
||||
----
|
||||
====
|
||||
|
||||
Querying and populating a __single__ domain object:
|
||||
The following exmaple queries and populates a single domain object:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
Mono<Actor> actor = reactiveCqlTemplate.queryForObject(
|
||||
@@ -316,9 +332,11 @@ Mono<Actor> actor = reactiveCqlTemplate.queryForObject(
|
||||
new Object[]{1212L},
|
||||
});
|
||||
----
|
||||
====
|
||||
|
||||
Querying and populating a number of domain objects:
|
||||
The following example queries and populates a number of domain objects:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
Flux<Actor> actors = reactiveCqlTemplate.query(
|
||||
@@ -332,13 +350,15 @@ 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
|
||||
duplication present in the two `RowMapper` anonymous inner classes and extract them 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:
|
||||
For example, it might be better to write the last code snippet as follows:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
public Flux<Actor> findAllActors() {
|
||||
@@ -357,33 +377,46 @@ enum ActorMapper implements RowMapper<Actor> {
|
||||
}
|
||||
}
|
||||
----
|
||||
====
|
||||
|
||||
[[cassandra.reactive.cql-template.examples.update]]
|
||||
==== Updating (INSERT/UPDATE/DELETE) with `ReactiveCqlTemplate`
|
||||
==== Updating INSERT, UPDATE, and 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.
|
||||
You can use the `execute(…)` method to perform insert, update, and delete operations. Parameter values are usually
|
||||
provided as variable arguments (var args) or as an `Object` array.
|
||||
|
||||
The following example shows how to use the `execute` method to do an insert operation:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
Mono<Boolean> applied = reactiveCqlTemplate.execute(
|
||||
"insert into t_actor (first_name, last_name) values (?, ?)",
|
||||
"Leonor", "Watling");
|
||||
----
|
||||
====
|
||||
|
||||
The following example shows how to use the `execute` method to do an update operation:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
Mono<Boolean> applied = reactiveCqlTemplate.execute(
|
||||
"update t_actor set last_name = ? where id = ?",
|
||||
"Banjo", 5276L);
|
||||
----
|
||||
====
|
||||
|
||||
The following example shows how to use the `execute` method to do a delete operation:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
Mono<Boolean> applied = reactiveCqlTemplate.execute(
|
||||
"delete from actor where id = ?",
|
||||
Long.valueOf(actorId));
|
||||
----
|
||||
====
|
||||
|
||||
include::exception-translation.adoc[]
|
||||
|
||||
@@ -392,106 +425,116 @@ during execution of the reactive sequence are emitted as error signals.
|
||||
|
||||
|
||||
[[cassandra.reactive.template]]
|
||||
== Introduction to ReactiveCassandraTemplate
|
||||
== Introduction to `ReactiveCassandraTemplate`
|
||||
|
||||
The `ReactiveCassandraTemplate` class, located in the package `org.springframework.data.cassandra`, is the central class
|
||||
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
|
||||
The `ReactiveCassandraTemplate` class, located in the `org.springframework.data.cassandra` package, is the central class
|
||||
in Spring Data's Cassandra support. It provides 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.
|
||||
NOTE: Once configured, `ReactiveCassandraTemplate` is thread-safe and can be reused across multiple instances.
|
||||
|
||||
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>>
|
||||
but you can also write your own custom converter. See "`<<mapping-chapter>>`"
|
||||
for more detailed information.
|
||||
|
||||
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.
|
||||
The `ReactiveCassandraTemplate` class implements the `ReactiveCassandraOperations` interface. As often as possible,
|
||||
the methods names `ReactiveCassandraOperations` match names in Cassandra to make the API familiar
|
||||
to 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
|
||||
For example, you can 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,
|
||||
NOTE: The preferred way to reference operations on a `ReactiveCassandraTemplate` instance is through 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 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>>.
|
||||
The default converter implementation for `ReactiveCassandraTemplate` is `MappingCassandraConverter`.
|
||||
While the `MappingCassandraConverter` can make use of additional metadata to specify the mapping of objects to rows,
|
||||
it can also convert 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, are explained in
|
||||
"`<<mapping.chapter>>`".
|
||||
|
||||
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 examples of how to work with the `CassandraTemplate` in the context of the Spring container.
|
||||
Another central feature of `CassandraTemplate` is exception translation. Exceptions thrown by the Cassandra
|
||||
Java driver are translated into Spring's portable Data Access Exception hierarchy. See
|
||||
"`<<cassandra.exception>>`" for more information.
|
||||
|
||||
[[cassandra.reactive.template.instantiating]]
|
||||
=== Instantiating ReactiveCassandraTemplate
|
||||
=== 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 an earlier example showed
|
||||
how to instantiate it directly. However, this section assumes that the template is used in a Spring module, so it also assumes
|
||||
that the Spring container is being used.
|
||||
|
||||
There are 2 easy ways to get a `ReactiveCassandraTemplate`, depending on how you load you Spring `ApplicationContext`.
|
||||
There are two ways to get a `ReactiveCassandraTemplate`, depending on how you load you Spring `ApplicationContext`:
|
||||
|
||||
* <<reactive-cassandra-template-autowiring>>
|
||||
* <<reactive-cassandra-template-application-context>>
|
||||
|
||||
[float]
|
||||
[[reactive-cassandra-template-autowiring]]
|
||||
==== Autowiring
|
||||
|
||||
You can autowire a `ReactiveCassandraTemplate` into your project, as the following example shows:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Autowired
|
||||
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
|
||||
in the same project), then use the `@Qualifier`annotation to designate which bean you want to Autowire.
|
||||
Like all Spring Autowiring, the preceding example assumes there is only one bean of type `ReactiveCassandraOperations` in the `ApplicationContext`.
|
||||
If you have multiple `ReactiveCassandraTemplate` beans (which can be the case if you are working with multiple keyspaces
|
||||
in the same project), you can use the `@Qualifier`annotation to designate which bean you want to autowire.
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
@Autowired
|
||||
@Qualifier("keyspaceTwoTemplateBeanId")
|
||||
private ReactiveCassandraOperations reactiveCassandraOperations;
|
||||
----
|
||||
====
|
||||
|
||||
[float]
|
||||
==== Bean Lookup with ApplicationContext
|
||||
[[reactive-cassandra-template-application-context]]
|
||||
==== Bean Lookup with `ApplicationContext`
|
||||
|
||||
You can also just lookup the `CassandraTemplate` bean from the `ApplicationContext`.
|
||||
You can also look up the `CassandraTemplate` bean from the `ApplicationContext`, as the following example shows:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
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,
|
||||
`ReactiveCassandraTemplate` provides a 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
|
||||
=== 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 `Converter`s with the `MappingCassandraConverter`.
|
||||
For example, `Converter<Row, Person>`.
|
||||
`CassandraTemplate` has several convenient methods for saving and inserting your objects. To have more
|
||||
fine-grained control over the conversion process, you can register Spring `Converter` instances 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.
|
||||
NOTE: The difference between insert and update operations is that an `INSERT` operation does 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
|
||||
the simple class name (not fully-qualified class name). The table to store the object can be overridden
|
||||
The simple case of using the INSERT operation is to save a POJO. In this case, the table name is determined by
|
||||
the simple class name (not the fully qualified class name). The table to store the object can be overridden by
|
||||
using mapping metadata.
|
||||
|
||||
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.
|
||||
The following example shows how to use the save operation and retrieve its contents:
|
||||
|
||||
.Inserting and retrieving objects using the `CassandraTemplate`
|
||||
====
|
||||
@@ -508,46 +551,47 @@ Mono<Person> queriedBob = reactiveCassandraTemplate.selectOneById(query(where("a
|
||||
----
|
||||
====
|
||||
|
||||
The insert/save operations available to you are listed below.
|
||||
The following insert and save operations are available:
|
||||
|
||||
* `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
|
||||
* `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`.
|
||||
|
||||
A similar set of update operations is listed below
|
||||
The following update operations are available:
|
||||
|
||||
* `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
|
||||
* `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`.
|
||||
|
||||
Then, there is always the old fashioned way. You can write your own CQL statements.
|
||||
You can also use the old fashioned way: You can write your own CQL statements, as the following example shows:
|
||||
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
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`.
|
||||
|
||||
You can also configure additional options (such as TTL, consistency level, and lightweight transactions)
|
||||
by using `InsertOptions` and `UpdateOptions`.
|
||||
|
||||
[[cassandra-template.insert-update.table]]
|
||||
==== Which table will my rows be inserted into?
|
||||
==== Into Which Table Are Rows Inserted?
|
||||
|
||||
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.
|
||||
You can manage the collection name that is used for operating on tables in two ways. The default table name
|
||||
is based on the simple class name changed to start with a lower-case letter. For example, an instance of
|
||||
the `com.example.Person` class is stored in a table called `person`. You can customize this by providing
|
||||
a different collection name by using the `@Table` annotation.
|
||||
|
||||
[[cassandra-template.update]]
|
||||
=== Updating rows in a table
|
||||
=== Updating Rows in a Table
|
||||
|
||||
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.
|
||||
The following example shows how to update a single account object in which we add a one-time $50.00 bonus to the balance
|
||||
by using the `+` assignment:
|
||||
|
||||
.Updating rows using `CasandraTemplate`
|
||||
====
|
||||
@@ -564,10 +608,9 @@ 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.
|
||||
In addition to the `Query` discussed earlier, we provide the update definition by 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 API for code styling purposes.
|
||||
|
||||
Read more about <<cassandra.template.update.methods,`Query` and `Update`>>.
|
||||
Most methods return the `Update` object to provide a fluent API for code styling purposes.
|
||||
|
||||
For more detail, see "`<<cassandra.template.update.methods>>`".
|
||||
|
||||
Reference in New Issue
Block a user