CHAPTER 10

USING SPRING DATA WITH CASSANDRA

Spring Data is designed for new data access technologies such as non-relational databases. The Spring Data Cassandra project adds Spring Data functionality to the Cassandra server. This chapter discusses how to use the Spring Data Cassandra project in Eclipse.

OVERVIEW OF THE SPRING DATA CASSANDRA PROJECT

The package for the conversion from Cassandra to Spring Data is org.springdata. cassandra.convert. The main interfaces and classes in the package are illustrated in Figure 10.1.

Figure 10.1
Main classes and interfaces in the org.springdata.cassandra.convert package.

Images

The main interfaces and classes in the org.springdata.cassandra.convert package are discussed in Table 10.1.

Table 10.1 Main Classes and Interfaces in the org.springdata.cassandra.convert Package

Images

The package for the Spring Data Cassandra configuration is org.springdata.cassandra. config.java. This package has just one class, AbstractCassandraConfiguration, which is the base class for Spring Data Cassandra configuration using JavaConfig, as illustrated in Figure 10.2.

Figure 10.2
The org.springdata.cassandra.config.java package.

Images

The package for the core classes in the Spring Data Cassandra project is org.springdata. cassandra.core. The package’s main classes and interfaces are illustrated in Figure 10.3.

Figure 10.3
Main classes and interfaces in the org.springdata.cassandra.core package.

Images

The main classes and interfaces in the org.springdata.cassandra.core package are discussed in Table 10.2.

Table 10.2 Main Classes and Interfaces in the org.springdata.cassandra.core Package

Images

The core package for running CQL queries is org.springdata.cassandra.cql.core. The package has the classes and interfaces shown in Figure 10.4.

Figure 10.4
Classes and interfaces in the org.springdata.cassandra.cql.core package.

Images

The main classes and interfaces in the org.springdata.cassandra.core package are discussed in Table 10.3.

Table 10.3 Main Classes and Interfaces in the org.springdata.cassandra.core Package

Images

The org.springdata.cassandra.mapping package defines the classes, interfaces, and annotation types for mapping a Spring Data domain object to Cassandra. Some of the annotation types in the package are illustrated in Figure 10.5.

Figure 10.5
Main annotation types in the org.springdata.cassandra.mapping package.

Images

The annotation types are discussed in Table 10.4.

Table 10.4 Main Annotation Types in the org.springdata.cassandra.mapping Package

Images

The org.springdata.cassandra.cql.config package defines classes and enums for CQL configuration. Some of the classes are illustrated in Figure 10.6.

Figure 10.6
Main classes in the org.springdata.cassandra.cql.config package.

Images

The classes are discussed in Table 10.5.

Table 10.5 Main Classes in the org.springdata.cassandra.cql.config Package

Images

SETTING THE ENVIRONMENT

To set the environment, you must install the following software:

Images Eclipse IDE for Java EE developers from http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/keplersr2

Images Apache Cassandra 2.04 or a later version from http://cassandra.apache.org/download/

Start Apache Cassandra with the following command:

cassandra –f

Create a Cassandra Keyspace called springdata with Cassandra-Cli. The placement_ strategy option specifies the strategy used for replica placement and the strategy_options option specifies the replication factor as 1 via the replication_factor property.

CREATE KEYSPACE springdata
with placement_strategy = 'org.apache.cassandra.locator.SimpleStrategy'
and strategy_options = {replication_factor:1};

Set the springdata keyspace as the working keyspace using the following command:

use springdata;

The output from creating and setting a keyspace is shown in Figure 10.7.

Figure 10.7
Creating a keyspace.

Images

Source: Microsoft Corporation.

Next, create a column family called catalog in Cassandra-Cli. One of the columns must be named key. The comparator, used for column names, and the key validation class, used for the primary key value, are set to UTF8Type. The column metadata specifies columns journal, publisher, edition, title, and author. The validation class for columns, which is used to validate column values, is set to UTF8Type.

CREATE COLUMN FAMILY catalog
WITH comparator = UTF8Type
AND key_validation_class=UTF8Type
AND column_metadata = [
{column_name: key, validation_class: UTF8Type},
{column_name: journal, validation_class: UTF8Type},
        {column_name: publisher, validation_class: UTF8Type},
        {column_name: edition, validation_class: UTF8Type},
        {column_name: title, validation_class: UTF8Type, index_type: KEYS},
        {column_name: author, validation_class: UTF8Type}
];

The output from the command is shown in Figure 10.8.

Figure 10.8
Creating a column family.

Images

Source: Microsoft Corporation.

CREATING A MAVEN PROJECT

Next, you will create a Maven project for Spring Data. Maven is a project management tool.

First, you need to create a Maven project in the Eclipse IDE. Follow these steps:

1. Select File > New > Other.

2. In the New dialog box, select Maven > Maven Project. Then click Next, as shown in Figure 10.9.

Figure 10.9
Selecting Maven > Maven Project.

Images

Source: Eclipse Foundation.

3. The New Maven Project wizard starts. Select the Create a Simple Project checkbox and the Use Default Workspace Location checkbox. Then click Next, as shown in Figure 10.10.

Figure 10.10
Selecting to create a simple project at the default location.

Images

Source: Eclipse Foundation.

4. In the Configure Project screen, specify a group ID (com.cassandra.core), an artifact ID (SpringCassandra or spring-cassandra), a version number (1.0), the packaging used (jar), and a name (SpringCassandra). Then click Finish, as shown in Figure 10.11. A Maven project (SpringCassandra or spring-cassandra) is created, as shown in Figure 10.12. (Note that the downloadable project for this chapter is spring-cassandra rather than SpringCassandra, which is used in the chapter.)

Figure 10.11
Configuring a new Maven project.

Images

Source: Eclipse Foundation.

Figure 10.12
The new Maven project.

Images

Source: Eclipse Foundation.

CONFIGURING THE MAVEN PROJECT

The Maven project includes a pom.xml file to specify the dependencies and build configuration for the project. In the pom.xml file, specify the dependencies listed in Table 10.6.

Table 10.6 Maven Project Dependencies

Images

Specify the maven-compiler-plugin and maven-eclipse-plugin plug-ins in the build configuration. The pom.xml file to use the Spring Data Cassandra project appears in Listing 10.1.

Listing 10.1 The pom.xml File

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.cassandra.core</groupId>
    <artifactId>SpringCassandra</artifactId>
    <version>1.0</version>
    <name>SpringCassandra</name>
    <repositories>
        <repository>
            <id>sonatype-nexus-snapshots</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>org.springdata</groupId>
            <artifactId>spring-data-cassandra</artifactId>
            <version>1.2.0.BUILD-SNAPSHOT</version>
        </dependency>
        <!-- Spring framework -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.5.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

CONFIGURING JavaConfig

Configure the Spring Data environment with POJOs using JavaConfig. The base class for Spring Data Cassandra configuration with JavaConfig is org.springdata.cassandra.config.java.AbstractCassandraConfiguration. In New Java Class wizard, create a Java class, SpringCassandraApplicationConfig, that extends the org.springdata.cassandra.config.java.AbstractCassandraConfiguration, class as shown in Figure 10.13.

Figure 10.13
Creating a JavaConfig class.

Images

Source: Eclipse Foundation.

Annotate the class with @Configuration, which indicates that the class is processed by the Spring container to generate bean definitions and service requests for the beans at runtime. The SpringCassandraApplicationConfig class must implement the inherited abstract method keyspace(). Return the keyspace name springdata as a String. The Spring Cassandra configuration class SpringCassandraApplicationConfig appears in Listing 10.2.

Listing 10.2 The Spring Configuration Class SpringCassandraApplicationConfig

package com.cassandra.config;
 
import java.beans.ConstructorProperties;
import org.springdata.cassandra.config.java.AbstractCassandraConfiguration;
import org.springdata.cassandra.convert.CassandraConverter;
import org.springdata.cassandra.convert.MappingCassandraConverter;
import org.springdata.cassandra.core.CassandraOperations;
import org.springdata.cassandra.core.CassandraSessionFactoryBean;
import org.springdata.cassandra.core.CassandraTemplate;
import org.springdata.cassandra.cql.config.KeyspaceAttributes;
import org.springdata.cassandra.cql.core.CassandraClusterFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.datastax.driver.core.Cluster;
 
@Configuration
public class SpringCassandraApplicationConfig extends
               AbstractCassandraConfiguration {
       public static final String KEYSPACE = "springdata";
        @Override
       protected String keyspace() {
              return KEYSPACE;
       }
}

CREATING A MODEL

Next, create the model class to use with the Spring Data Cassandra project. A domain object to be persisted to Cassandra server must be annotated with org.springdata. cassandra.mapping.Table. In the New Java Class wizard, create a POJO class named Catalog, as shown in Figure 10.14.

Figure 10.14
Creating a model POJO class named Catalog.

Images

Source: Eclipse Foundation.

Add fields for key, journal, edition, publisher, title, and author and the corresponding get/set methods. Annotate the id field with @Id. Add constructors that may be used to construct a Catalog instance. The Catalog entity appears in Listing 10.3.

Listing 10.3 The Catalog Entity

package com.cassandra.model;
import org.springframework.data.annotation.Id;
import org.springdata.cassandra.mapping.Table;
@Table(name = "catalog")
public class Catalog {
       @Id
       private String key;
       private String journal;
       private String publisher;
       private String edition;
       private String title;
       private String author;
 
       public Catalog() {}
 
       public Catalog(String key, String journal, String publisher,
              String edition, String title, String author) {
              this.key = key;
              this.journal = journal;
              this.publisher = publisher;
              this.edition = edition;
              this.title = title;
              this.author = author;
       }
       public String getKey() {
              return key;
       }
       public void setKey(String key) {
              this.key = key;
       }
       public String getJournal() {
              return journal;
       }
       public void setJournal(String journal) {
              this.journal = journal;
       }
       public String getPublisher() {
              return publisher;
       }
       public void setPublisher(String publisher) {
              this.publisher = publisher;
       }
       public String getEdition() {
              return edition;
       }
       public void setEdition(String edition) {
       this.edition = edition;
       }
       public String getTitle() {
              return title;
       }
       public void setTitle(String title) {
              this.title = title;
       }
       public String getAuthor() {
              return author;
       }
       public void setAuthor(String author) {
              this.author = author;
       }
}

The directory structure of the SpringCassandra project is shown in Figure 10.15.

Figure 10.15
The directory structure of the SpringCassandra project.

Images

Source: Eclipse Foundation.

USING SPRING DATA WITH CASSANDRA WITH TEMPLATE

The common CRUD operations on a Cassandra data source may be performed using the org.springdata.cassandra.core.CassandraOperations interface. The org.springdata. cassandra.core.CassandraTemplate class implements the CassandraOperations interface. In this section, you will run CRUD operations on Cassandra using the CassandraTemplate class. Create a Java client class (CassandraClient) for the Cassandra CRUD operations in New Java Class wizard, as shown in Figure 10.16.

Figure 10.16
Creating a Java client class.

Images

Source: Eclipse Foundation.

The directory structure of the SpringCassandra project is shown in Figure 10.17.

Figure 10.17
The directory structure of SpringCassandra project.

Images

Source: Eclipse Foundation.

You can obtain a CassandraTemplate instance obtained using ApplicationContext. Create an ApplicationContext as follows:

ApplicationContext context = new
AnnotationConfigApplicationContext(SpringCassandraApplicationConfig.class);

The getBean(Class requiredType) method returns a named bean of the specified type. The class type is CassandraOperations.class.

CassandraOperations ops = context.getBean(CassandraOperations.class);

FINDING OUT ABOUT THE CASSANDRA CLUSTER

The org.springdata.cassandra.cql.core.CqlOperations interface provides the overloaded describeRing() method to find the Cassandra cluster topology. Obtain a CqlOperations instance from the CassandraOperations instance using the getCqlOperations() method and invoke the describeRing() method to obtain a List<RingMember> instance. Iterate over the List to output the individual Cassandra node description.

for (RingMember member : ops.getCqlOperations().describeRing()) {
       System.out.println(member.toString());
}

Output the table name used for the specified entity class by the template using the getTableName(Class<?> entityClass) method in CassandraOperations.

System.out.println("Table name: " + ops.getTableName(Catalog.class));

To run the CassandraClient application, right-click the CassandraClient.java class in Package Explorer and select Run As > Java Application, as shown in Figure 10.18.

Figure 10.18
Running the CassandraClient application.

Images

Source: Eclipse Foundation.

A description of the Cassandra node connected in the cluster is output, including the host name, address, data center, and rack. The Cassandra table name used for the Catalog entity class is also output, as shown in Figure 10.19.

Figure 10.19
Cassandra node description.

Images

Source: Eclipse Foundation.

RUNNING CASSANDRA CRUD OPERATIONS

You can use the CassandraOperations instance to perform various create, read, update, delete (CRUD) operations on a domain object stored in the Cassandra server. Add the methods discussed in Table 10.7 to the CassandraClient class and invoke the methods from the main method.

Table 10.7 CassandraClient Class Methods

Images

In subsequent sections, you will invoke these methods for CRUD operations. Comment out the method invocations not to be run in an application. For example, to invoke only the saveNew() method, uncomment the saveNew() method and comment out method invocations for all other methods when the application is run.

Save Operations

The CassandraOperations interface provides several methods for adding new row(s) to Cassandra. These are listed in Table 10.8.

Table 10.8 CassandraOperations Interface Methods for Adding New Rows

Images

In the saveNew() method, create an instance of the entity class Catalog.

Catalog catalog1 = new Catalog("catalog1", "Oracle Magazine",
"Oracle Publishing", "November-December 2013",
"Engineering as a Service", "David A. Kelly");

Invoke the saveNew(T entity) method in CassandraOperations to save the Catalog entity instance.

ops.saveNew(catalog1);

Run the CassandraClient application to invoke the saveNew() method and save a new row in the catalog table. Then run the following command in Cassandra-Cli:

list catalog;

The output lists the row added, as shown in Figure 10.20.

Figure 10.20
Listing the new row added.

Images

Source: Microsoft Corporation.

In the saveNewInBatch() method, use the saveNewInBatch(Iterable<T> entities) method to save a batch of rows. First create a HashSet instance, in which you will add the Catalog entity instances.

HashSet<Catalog> entities = new HashSet();

Create instances of the Catalog entity and add the entity instances to the HashSet using the add(E e) method.

Catalog catalog2 = new Catalog("catalog2", "Oracle Magazine",
"Oracle Publishing", "November-December 2013",
"Quintessential and Collaborative", "Tom Haunert");
Catalog catalog3 = new Catalog("catalog3", "Oracle Magazine",
"Oracle Publishing", "November-December 2013", "", "");
Catalog catalog4 = new Catalog("catalog4", "Oracle Magazine",
"Oracle Publishing", "November-December 2013", "", "");
Catalog catalog5 = new Catalog("catalog5", "Oracle Magazine",
"Oracle Publishing", "November-December 2013", "", "");
Catalog catalog6 = new Catalog("catalog6", "Oracle Magazine",
"Oracle Publishing", "November-December 2013", "", "");
entities.add(catalog2);
entities.add(catalog3);
entities.add(catalog4);
entities.add(catalog5);
entities.add(catalog6);

Invoke the saveNewInBatch(Iterable<T> entities) method to save the HashSet. The batch save is not applied until the saveNewInBatch() method is invoked on the entities.

ops.saveNewInBatch(entities);

Then run the list catalog command in Cassandra-Cli to list the batch of rows added, as shown in Figure 10.21.

Figure 10.21
Listing the batch of rows added.

Images

Source: Microsoft Corporation.

Find Operations

The CassandraOperations interface provides several methods to find row(s) from Cassandra, as listed in Table 10.9.

Table 10.9 CassandraOperations Interface Methods for Finding Rows

Images

In this section, you will find the rows added to Cassandra using the different find methods in CassandraOperations. In the findAll() method in CassandraClient, invoke the findAll(Class<T> entityClass) method in CassandraOperations with Catalog.class as argument. This method will return a list, from which you will get an Iterator to use over the result set.

Iterator<Catalog> iter = ops.findAll(Catalog.class).iterator();

Using a while loop, iterate over the result set and output the column values for each of the rows.

while (iter.hasNext()) {
        Catalog catalog = iter.next();
        System.out.println(catalog.getKey());
        System.out.println(catalog.getJournal());
        System.out.println(catalog.getPublisher());
        System.out.println(catalog.getEdition());
        System.out.println(catalog.getTitle());
        System.out.println(catalog.getAuthor());
}

Invoke the findAll() method from the main method to output the rows stored in Cassandra, as shown in Figure 10.22.

Figure 10.22
Finding all rows.

Images

Source: Eclipse Foundation.

In the findAllSpecifiedIds() method in CassandraClient, invoke the findAll(Class<T> entityClass,Iterable<?> ids) method in CassandraOperations with Catalog.class as the first argument and a HashSet of row IDs as the second argument. This method will return a list, from which you will get an Iterator to use over the result set.

HashSet<String> ids = new HashSet();
ids.add("catalog1");
ids.add("catalog2");
Iterator<Catalog> iter = ops.findAll(Catalog.class, ids).iterator();

Using a while loop, iterate over the result set and output the column values for each of the rows.

while (iter.hasNext()) {
        Catalog catalog = iter.next();
        System.out.println(catalog.getKey());
        System.out.println(catalog.getJournal());
        System.out.println(catalog.getPublisher());
        System.out.println(catalog.getEdition());
        System.out.println(catalog.getTitle());
        System.out.println(catalog.getAuthor());
}

Invoke the findAllSpecifiedIds() method from the main method to output the rows stored in Cassandra, as shown in Figure 10.23. The output for findAllSpecifiedIds() and findAll is the same because you specified all IDs in findAllSpecifiedIds().

Figure 10.23
Finding Cassandra table rows by all specified IDs.

Images

Source: Eclipse Foundation.

In the findById() method in CassandraClient, invoke the findById(Class<T> entityClass, Object id) method to find a row with Catalog.class as the first argument and "catalog1" as the second argument. This method will return a Catalog entity instance. Output the column values for the row selected.

System.out.println(catalog.getKey());
System.out.println(catalog.getJournal());
System.out.println(catalog.getPublisher());
System.out.println(catalog.getEdition());
System.out.println(catalog.getTitle());
System.out.println(catalog.getAuthor());

Invoke the findById() method from the main method to output the catalog1 row stored in Cassandra, as shown in Figure 10.24.

Figure 10.24
Finding a Cassandra table row by ID.

Images

Source: Eclipse Foundation.

In the findAllByCql() method in CassandraClient, invoke the find(Class<T> entityClass, String cql) method in CassandraOperations to select rows using a CQL query. Specify Catalog.class as the first argument. As the second argument, specify a CQL query "SELECT * FROM catalog". Then invoke the findAll() method to return an Iterator for the result set.

Iterator<Catalog> iter = ops.findAll(Catalog.class).iterator();

Using a while loop, iterate over the result set and output the column values for each of the rows.

while (iter.hasNext()) {
        Catalog catalog = iter.next();
        System.out.println(catalog.getKey());
        System.out.println(catalog.getJournal());
        System.out.println(catalog.getPublisher());
        System.out.println(catalog.getEdition());
        System.out.println(catalog.getTitle());
        System.out.println(catalog.getAuthor());
}

Invoke the findAllByCql() method from the main method to output the rows stored in Cassandra, as shown in Figure 10.25. The output for findAllByCql() is the same as for findAllSpecifiedIds() and findAll.

Figure 10.25
Finding all table rows by CQL.

Images

Source: Eclipse Foundation.

In the findOneByCql() method in CassandraClient, invoke the findOne(Class<T> entityClass, String cql) method to find a row with Catalog.class as the first argument and the CQL query "SELECT * from catalog WHERE key='catalog1'" as the second argument. Then execute the method to return a Catalog entity instance. Output the column values for the row selected.

System.out.println(catalog.getKey());
System.out.println(catalog.getJournal());
System.out.println(catalog.getPublisher());
System.out.println(catalog.getEdition());
System.out.println(catalog.getTitle());
System.out.println(catalog.getAuthor());

Invoke the findOneByCql() method from the main method to output the catalog1 row stored in Cassandra, as shown in Figure 10.26. The output for findOneByCql() is the same as for findById() because you have specified the same ID, 'catalog1'.

Figure 10.26
Finding one table row by CQL.

Images

Source: Eclipse Foundation.

Exists and Count Operations

The exists(Class<T> entityClass, Object id) method in CassandraOperations finds whether an entity exists in the Cassandra database. In the exists() method in Cassandra-Client, invoke the exists(Class<T> entityClass, Object id) method with Catalog. class as the first argument and "catalog2" as the second argument to find out if the catalog2 ID exists in the Cassandra table catalog. Invoke the execute() method to run the operation. The exists(Class<T> entityClass, Object id) method returns a Boolean object. Invoke the booleanValue() method on the Boolean object to find if the catalog2 row exists.

System.out.println("The catalog entry with id catalog2 exists: "+ ops.exists
(Catalog.class, "catalog2"));

The countAll(Class<T> entityClass) method in CassandraOperations returns Long for the number of rows for a specified entity. In the countRows() method in CassandraClient, invoke the countAll(Class<T> entityClass) method with Catalog.class as the argument.

System.out.println("Number of rows: " + ops.countAll(Catalog.class));

In the next run of the CassandraClient application, invoke the exists() method and the countRows() method. The output indicates that Cassandra has six rows and that the catalog2 row exists, as shown in Figure 10.27.

Figure 10.27
Finding if a Cassandra table row exists.

Images

Source: Eclipse Foundation.

Update Operations

The CassandraOperations interface provides two methods for updating row(s) to Cassandra, as listed in Table 10.10.

Table 10.10 CassandraOperations Interface Methods for Updating Rows

Images

In the update() method in CassandraClient creates an instance of Catalog with the updated column values.

Catalog catalog1 = new Catalog("catalog1", "Oracle Magazine","Oracle-Publishing",
"11/12 2013", "Engineering as a Service","Kelly, David A.");

Invoke the save(T entity) method to update the catalog1 row.

ops.save(catalog1);

Uncomment the update() method invocation in the main method. When the application is run, the catalog1 row is updated. Then run the list catalog command in cassandra-cli to list the updated row catalog1, as shown in Figure 10.28.

Figure 10.28
Listing the updated row.

Images

Source: Microsoft Corporation.

In the updateInBatch() method in CassandraClient, create two instances of Catalog with the updated column values.

Catalog catalog2 = new Catalog("catalog2", "Oracle Magazine",
"Oracle Publishing", "November-December 2013",
"Quintessential and Collaborative", "Haunert, Tom");
 
Catalog catalog3 = new Catalog("catalog3", "Oracle Magazine",
"Oracle-Publishing", "Nov-Dec 2013", "", "");

Create a HashSet and add the entity instances to it.

HashSet<Catalog> entities = new HashSet();
entities.add(catalog2);
entities.add(catalog3);

Invoke the saveNewInBatch(Iterable<T> entities) method to save the HashSet object. Uncomment the updateInBatch() method invocation in the main method. When the application is run, the catalog2 and catalog3 rows are updated. Next, run the list catalog command in Cassandra-Cli to list the updated rows catalog2 and catalog3, as shown in Figure 10.29.

Figure 10.29
Listing table rows updated in batch.

Images

Source: Microsoft Corporation.

Remove Operations

CassandraOperations provides several methods for removing row(s) from Cassandra, as listed in Table 10.11.

Table 10.11 CassandraOperations Interface Methods for Removing Rows

Images

In the deleteById() method, invoke the deleteById(Class<T> entityClass, Object id) method with Catalog.class as the first argument and catalog3 as the second argument.

ops.deleteById(Catalog.class, "catalog3");

When the CassandraClient application is run with the deleteById() method invocation uncommented, the catalog3 row is deleted from the catalog table. Next, run the list catalog command in Cassandra-Cli to list the catalog3 row columns as deleted, as shown in Figure 10.30.

Figure 10.30
Listing deleted rows by ID.

Images

Source: Microsoft Corporation.

In the deleteByIdInBatch() method in CassandraClient, invoke the deleteByIdInBatch (Class<T> entityClass, Iterable<?> ids) method with Catalog.class as the first argument and a HashSet of IDs consisting of catalog1 and catalog2 as the second argument.

HashSet<String> ids = new HashSet();
ids.add("catalog1");
ids.add("catalog2");
ops.deleteByIdInBatch(Catalog.class, ids);

In the delete() method in CassandraClient, invoke the delete(T entity) with a Catalog instance for the catalog4 ID as the argument.

Catalog catalog4 = new Catalog("catalog4", "Oracle Magazine",
"Oracle Publishing", "November-December 2013", "", "");
ops.delete(catalog4);

When the CassandraClient application is run with the deleteByIdInBatch() method and delete() method invocations uncommented, the catalog1 and catalog2 rows are deleted from the catalog table. The catalog4 ID is also deleted. Next, run the list catalog command in Cassandra-Cli to list the catalog1, catalog2, catalog3, and catalog4 row columns as deleted. (The catalog3 row column was deleted earlier using the deleteById() method.) See Figure 10.31.

Figure 10.31
Listing rows deleted by ID in a batch.

Images

Source: Microsoft Corporation.

In the deleteInBatch() method in CassandraClient, invoke the deleteInBatch (Iterable<T>entities) method with a HashSet of entities consisting of catalog5 and catalog6 as the second argument. Then invoke the execute() method to apply the deletion.

HashSet<Catalog> entities = new HashSet();
Catalog catalog5 = new Catalog("catalog5", "Oracle Magazine",
"Oracle Publishing", "November-December 2013", "", "");
Catalog catalog6 = new Catalog("catalog6", "Oracle Magazine",
"Oracle Publishing", "November-December 2013", "", "");
entities.add(catalog5);
entities.add(catalog6);
ops.deleteInBatch(entities);

Next, run the list catalog command in Cassandra-Cli to list the catalog5 and catalog6 row columns as deleted in addition to the other catalog IDs deleted earlier, as shown in Figure 10.32.

Figure 10.32
Listing rows deleted in batch.

Images

Source: Microsoft Corporation.

The CassandraClient application appears in Listing 10.4.

Listing 10.4 The CassandraClient Application

package com.cassandra.core;
 
import java.util.HashSet;
import java.util.Iterator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.cassandra.config.SpringCassandraApplicationConfig;
import com.cassandra.model.Catalog;
import org.springdata.cassandra.core.CassandraOperations;
import org.springdata.cql.core.RingMember;
 
public class CassandraClient {
 
    static CassandraOperations ops;
 
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(
                 SpringCassandraApplicationConfig.class);
        ops = context.getBean(CassandraOperations.class);
//        for (RingMember member : ops.getCqlOperations().describeRing()) {
//            System.out.println(member.toString());
//        }
        System.out.println("Table name: " + ops.getTableName(Catalog.class));
//        saveNew();
//        saveNewInBatch();
//        findAll();
//        findAllSpecifiedIds();
//        findById();
//        findAllByCql();
//        findOneByCql();
//        countRows();
//        exists();
//        update();
//        updateInBatch();
//        deleteById();
//        deleteByIdInBatch();
//        delete();
//        deleteInBatch();
    }
 
    private static void saveNew() {
        Catalog catalog1 = new Catalog("catalog1", "Oracle Magazine",
                "Oracle Publishing", "November-December 2013",
                "Engineering as a Service", "David A. Kelly");
        ops.saveNew(catalog1);
    }
 
    private static void saveNewInBatch() {
        HashSet<Catalog> entities = new HashSet();
        Catalog catalog2 = new Catalog("catalog2", "Oracle Magazine",
                "Oracle Publishing", "November-December 2013",
                "Quintessential and Collaborative", "Tom Haunert");
        Catalog catalog3 = new Catalog("catalog3", "Oracle Magazine",
                "Oracle Publishing", "November-December 2013", "", "");
        Catalog catalog4 = new Catalog("catalog4", "Oracle Magazine",
                "Oracle Publishing", "November-December 2013", "", "");
        Catalog catalog5 = new Catalog("catalog5", "Oracle Magazine",
                "Oracle Publishing", "November-December 2013", "", "");
        Catalog catalog6 = new Catalog("catalog6", "Oracle Magazine",
                "Oracle Publishing", "November-December 2013", "", "");
        entities.add(catalog2);
        entities.add(catalog3);
        entities.add(catalog4);
        entities.add(catalog5);
        entities.add(catalog6);
        ops.saveNewInBatch(entities);
    }
 
    private static void countRows() {
        System.out.println("Number of rows: " + ops.countAll(Catalog.class));
    }
 
    private static void exists() {
        Catalog catalog3 = new Catalog("catalog1", "Oracle Magazine",
                "Oracle Publishing", "November-December 2013", "", "");
        //System.out.println("The catalog3 entity exists: "+
ops.exists(catalog3);
        //System.out.println("
");
        System.out.println("The catalog entry with id catalog2 exists: " +
ops.exists(Catalog.class, "catalog2"));
    }
 
    private static void findAll() {
        Iterator<Catalog> iter = ops.findAll(Catalog.class).iterator();
        while (iter.hasNext()) {
            Catalog catalog = iter.next();
            System.out.println(catalog.getKey());
            System.out.println("
");
            System.out.println(catalog.getJournal());
            System.out.println("
");
            System.out.println(catalog.getPublisher());
            System.out.println("
");
            System.out.println(catalog.getEdition());
            System.out.println("
");
            System.out.println(catalog.getTitle());
            System.out.println("
");
            System.out.println(catalog.getAuthor());
        }
    }
 
    private static void findAllSpecifiedIds() {
        HashSet<String> ids = new HashSet();
        ids.add("catalog1");
        ids.add("catalog2");
        Iterator<Catalog> iter = ops.findAll(Catalog.class, ids).iterator();
 
        while (iter.hasNext()) {
            Catalog catalog = iter.next();
            System.out.println(catalog.getKey());
            System.out.println("
");
            System.out.println(catalog.getJournal());
            System.out.println("
");
            System.out.println(catalog.getPublisher());
            System.out.println("
");
            System.out.println(catalog.getEdition());
            System.out.println("
");
            System.out.println(catalog.getTitle());
            System.out.println("
");
            System.out.println(catalog.getAuthor());
        }
    }
    private static void findById() {
        Catalog catalog = ops.findById(Catalog.class, "catalog1");
        System.out.println(catalog.getKey());
        System.out.println("
");
        System.out.println(catalog.getJournal());
        System.out.println("
");
        System.out.println(catalog.getPublisher());
        System.out.println("
");
        System.out.println(catalog.getEdition());
        System.out.println("
");
        System.out.println(catalog.getTitle());
        System.out.println("
");
        System.out.println(catalog.getAuthor());
    }
 
    private static void findAllByCql() {
        Iterator<Catalog> iter = ops.find(Catalog.class,
                "SELECT * FROM catalog").iterator();
        while (iter.hasNext()) {
            Catalog catalog = iter.next();
            System.out.println(catalog.getKey());
            System.out.println("
");
            System.out.println(catalog.getJournal());
            System.out.println("
");
            System.out.println(catalog.getPublisher());
            System.out.println("
");
            System.out.println(catalog.getEdition());
            System.out.println("
");
            System.out.println(catalog.getTitle());
            System.out.println("
");
            System.out.println(catalog.getAuthor());
        }
    }
 
    private static void findOneByCql() {
        Catalog catalog = ops.findOne(Catalog.class,
                "SELECT * from catalog WHERE key='catalog1'");
        System.out.println(catalog.getKey());
        System.out.println("
");
        System.out.println(catalog.getJournal());
        System.out.println("
");
        System.out.println(catalog.getPublisher());
        System.out.println("
");
        System.out.println(catalog.getEdition());
        System.out.println("
");
        System.out.println(catalog.getTitle());
        System.out.println("
");
        System.out.println(catalog.getAuthor());
    }
 
    private static void update() {
        Catalog catalog1 = new Catalog("catalog1", "Oracle Magazine",
                "Oracle-Publishing", "11/12   2013", "Engineering as a Service",
                "Kelly, David A.");
        ops.save(catalog1);
    }
 
    private static void updateInBatch() {
        HashSet<Catalog> entities = new HashSet();
        Catalog catalog2 = new Catalog("catalog2", "Oracle Magazine",
                "Oracle Publishing", "November-December 2013",
                "Quintessential and Collaborative", "Haunert, Tom");
        Catalog catalog3 = new Catalog("catalog3", "Oracle Magazine",
                "Oracle-Publishing", "Nov-Dec 2013", "", "");
        entities.add(catalog2);
        entities.add(catalog3);
        ops.saveInBatch(entities);
    }
    private static void deleteById() {
        ops.deleteById(Catalog.class, "catalog3");
    }
 
    private static void deleteByIdInBatch() {
        HashSet<String> ids = new HashSet();
        ids.add("catalog1");
        ids.add("catalog2");
        ops.deleteByIdInBatch(Catalog.class, ids);
    }
 
    private static void delete() {
        Catalog catalog4 = new Catalog("catalog4", "Oracle Magazine",
                "Oracle Publishing", "November-December 2013", "", "");
        ops.delete(catalog4);
    }
 
    private static void deleteInBatch() {
        HashSet<Catalog> entities = new HashSet();
        Catalog catalog5 = new Catalog("catalog5", "Oracle Magazine",
                "Oracle Publishing", "November-December 2013", "", "");
        Catalog catalog6 = new Catalog("catalog6", "Oracle Magazine",
                "Oracle Publishing", "November-December 2013", "", "");
        entities.add(catalog5);
        entities.add(catalog6);
        ops.deleteInBatch(entities);
    }
}

SUMMARY

In this chapter, you used the Spring Data project for Cassandra to run CRUD operations in Apache Cassandra using a Maven project.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.106.233