Using the CassandraTemplate from Spring Data – 使用来自Spring Data的CassandraTemplate

最后修改: 2015年 12月 24日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This is the second article of the Spring Data Cassandra article series. In this article we will mainly focus on CassandraTemplate and CQL queries in the data access layer. You can read more about Spring Data Cassandra in the first article in the series.

这是Spring Data Cassandra系列文章的第二篇文章。在这篇文章中,我们将主要关注CassandraTemplate和数据访问层的CQL查询。您可以在该系列的第一篇文章中阅读更多有关Spring Data Cassandra的内容。

Cassandra Query Language (CQL) is the query language for the Cassandra database and CqlTemplate is the low-level data access template in Spring Data Cassandra – it conveniently exposes data manipulation related operations to execute CQL statements.

Cassandra查询语言(CQL)是Cassandra数据库的查询语言,CqlTemplate是Spring Data Cassandra中的底层数据访问模板–它方便地暴露了执行CQL语句的数据操作相关操作。

CassandraTemplate builds on top of the low level CqlTemplate and provides a simple way to query domain objects and map the objects to a persisted data structure in Cassandra.

CassandraTemplate建立在低级别的CqlTemplate之上,提供了一种简单的方法来查询领域对象并将对象映射到Cassandra中的持久化数据结构。

Let’s start with the configuration and then dive into examples of using the two templates.

让我们从配置开始,然后深入了解使用这两个模板的例子。

2. CassandraTemplate Configuration

2.CassandraTemplateConfiguration

CassandraTemplate is available in the Spring context because our main Cassandra Spring config is extending AbstractCassandraConfiguration:

CassandraTemplate在Spring上下文中可用,因为我们的主Cassandra Spring配置正在扩展AbstractCassandraConfiguration。

@Configuration
@EnableCassandraRepositories(basePackages = "com.baeldung.spring.data.cassandra.repository")
public class CassandraConfig extends AbstractCassandraConfiguration { ... }

We can then simple wire in the template – either by its exact type, CassandraTemplate, or as the more generic interface CassandraOperations:

然后,我们可以简单地接入模板–既可以通过其确切的类型CassandraTemplate,也可以作为更通用的接口CassandraOperations。

@Autowired
private CassandraOperations cassandraTemplate;

3. Data Access Using CassandraTemplate

3.使用CassandraTemplate的数据访问

Let’s use the CassandraTemplate defined above in our data access layer module to work with data persistent.

让我们在数据访问层模块中使用上面定义的CassandraTemplate来处理数据的持久性。

3.1. Saving a New Book

3.1.保存一本新书

We can save a new book to our book store:

我们可以把一本新书保存在我们的书店里。

Book javaBook = new Book(
  UUIDs.timeBased(), "Head First Java", "O'Reilly Media",
  ImmutableSet.of("Computer", "Software"));
cassandraTemplate.insert(javaBook);

Then we can check the availability of the inserted book in the database:

然后我们可以在数据库中检查插入的书的可用性。

Select select = QueryBuilder.select().from("book")
  .where(QueryBuilder.eq("title", "Head First Java"))
  .and(QueryBuilder.eq("publisher", "O'Reilly Media"));
Book retrievedBook = cassandraTemplate.selectOne(select, Book.class);

We are using a Select QueryBuilder here, to be mapped to the selectOne() in cassandraTemplate. We will discuss the QueryBuilder in more depth in the CQL queries section.

我们在这里使用了一个Select QueryBuilder,以映射到cassandraTemplate中的selectOne()。我们将在CQL查询部分更深入地讨论QueryBuilder

3.2. Saving Multiple Books

3.2.保存多本图书

We can save multiple books to our book store at once using a list:

我们可以使用一个列表一次保存多本图书到我们的书店。

Book javaBook = new Book(
  UUIDs.timeBased(), "Head First Java", "O'Reilly Media",
  ImmutableSet.of("Computer", "Software"));
Book dPatternBook = new Book(
  UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media",
  ImmutableSet.of("Computer", "Software"));
List<Book> bookList = new ArrayList<Book>();
bookList.add(javaBook);
bookList.add(dPatternBook);
cassandraTemplate.insert(bookList);

3.3. Updating an Existing Book

3.3.更新现有的书

Lat’s start by inserting a new book:

我们从插入一本新书开始。

Book javaBook = new Book(
  UUIDs.timeBased(), "Head First Java", "O'Reilly Media",
  ImmutableSet.of("Computer", "Software"));
cassandraTemplate.insert(javaBook);

Let’s fetch the book:

我们去拿书吧。

Select select = QueryBuilder.select().from("book");
Book retrievedBook = cassandraTemplate.selectOne(select, Book.class);

Then let’s add some additional tags to the retrieved book:

然后让我们为检索到的书添加一些额外的标签:

retrievedBook.setTags(ImmutableSet.of("Java", "Programming"));
cassandraTemplate.update(retrievedBook);

3.4. Deleting an Inserted Book

3.4.删除插入的书籍

Let’s insert a new book:

让我们插入一本新书。

Book javaBook = new Book(
  UUIDs.timeBased(), "Head First Java", "O'Reilly Media",
  ImmutableSet.of("Computer", "Software"));
cassandraTemplate.insert(javaBook);

Then delete the book:

然后删除该书。

cassandraTemplate.delete(javaBook);

3.5. Deleting All Books

3.5.删除所有书籍

Let’s now insert some new books:

现在让我们插入一些新书。

Book javaBook = new Book(
  UUIDs.timeBased(), "Head First Java", "O'Reilly Media",
  ImmutableSet.of("Computer", "Software"));
Book dPatternBook = new Book(
  UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", 
  ImmutableSet.of("Computer", "Software"));
cassandraTemplate.insert(javaBook);
cassandraTemplate.insert(dPatternBook);

Then delete the all the books:

然后删除所有的书。

cassandraTemplate.deleteAll(Book.class);

4. Data Access Using CQL Queries

4.使用CQL查询的数据访问

It is always possible to use CQL queries for data manipulation in the data access layer. CQL query handing is performed by the CqlTemplate class, allowing us to execute custom queries as required.

在数据访问层,总是可以使用CQL查询来进行数据操作。CQL查询的处理是由CqlTemplate类执行的,允许我们根据需要执行自定义查询。

However, as CassandraTemplate class is an extension of CqlTemplate, we can use it directly to execute those queries.

然而,由于CassandraTemplate类是CqlTemplate的扩展,我们可以直接使用它来执行这些查询。

Let’s look at the different methods we can use to manipulate data using CQL queries.

让我们来看看我们可以使用不同的方法来使用CQL查询来操作数据。

4.1. Using QueryBuilder

4.1.使用QueryBuilder

QueryBuilder can be used to build a query for data manipulation in database. Almost all the standard manipulations can be built up using the out-of-the-box building blocks:

QueryBuilder可用于建立数据库中数据操作的查询。几乎所有的标准操作都可以使用开箱即用的构建模块建立起来。

Insert insertQueryBuider = QueryBuilder.insertInto("book")
 .value("isbn", UUIDs.timeBased())
 .value("title", "Head First Java")
 .value("publisher", "OReilly Media")
 .value("tags", ImmutableSet.of("Software"));
cassandraTemplate.execute(insertQueryBuider);

If you look closely at the code snippet, you may notice that the execute() method is used instead of the relevant operation type (insert, delete, etc.). This is because the type of query is defined by the output of the QueryBuilder.

如果你仔细观察代码片段,你可能会注意到execute()方法被使用,而不是相关操作类型(插入、删除等)。这是因为查询的类型是由QueryBuilder的输出定义的。

4.2. Using PreparedStatements

4.2.使用PreparedStatements

Even though PreparedStatements can be used for any case, this mechanism is usually recommended for multiple inserts for high-speed ingestion.

尽管PreparedStatements可用于任何情况,但这种机制通常被推荐用于高速摄入的多个插入。

A PreparedStatement is prepared only once, helping ensure high performance:

一个 PreparedStatement只准备一次,有助于确保高性能。

UUID uuid = UUIDs.timeBased();
String insertPreparedCql = 
  "insert into book (isbn, title, publisher, tags) values (?, ?, ?, ?)";
List<Object> singleBookArgsList = new ArrayList<>();
List<List<?>> bookList = new ArrayList<>();
singleBookArgsList.add(uuid);
singleBookArgsList.add("Head First Java");
singleBookArgsList.add("OReilly Media");
singleBookArgsList.add(ImmutableSet.of("Software"));
bookList.add(singleBookArgsList);
cassandraTemplate.ingest(insertPreparedCql, bookList);

4.3. Using CQL Statements

4.3.使用CQL语句

We can directly use CQL statements to query data as follows:

我们可以直接使用CQL语句来查询数据,如下所示。

UUID uuid = UUIDs.timeBased();
String insertCql = "insert into book (isbn, title, publisher, tags) 
  values (" + uuid + ", 'Head First Java', 'OReilly Media', {'Software'})";
cassandraTemplate.execute(insertCql);

5. Conclusion

5.结论

In this article, we examined various data manipulation strategies using Spring Data Cassandra, including CassandraTemplate and CQL queries.

在这篇文章中,我们研究了使用Spring Data Cassandra的各种数据操作策略,包括CassandraTemplate和CQL查询。

The implementation of the above code snippets and examples can be found in my GitHub project – this is a Maven-based project, so it should be easy to import and run as it is.

我的GitHub项目中可以找到上述代码段和示例的实现–这是一个基于Maven的项目,所以应该很容易导入并按原样运行。