Getting Started

Apache Cassandra 的 Spring Data 要求 Apache Cassandra 2.1 或更高版本和 Datastax Java Driver 4.0 或更高版本。快速设置和引导工作环境的一种简便方法是在 Spring Tools 中创建基于 Spring 的项目或使用 start.spring.io

Examples Repository

为了了解该库的工作原理,您可以下载并使用 several examples

Hello World

首先,您需要设置正在运行的 Apache Cassandra 服务器。请参阅 Apache Cassandra Quick Start Guide 以了解有关如何启动 Apache Cassandra 的说明。一旦安装,启动 Cassandra 通常是执行以下命令的问题: CASSANDRA_HOME/bin/cassandra -f

要在 STS 中创建一个 Spring 项目,请转到文件 → 新建 → Spring 模板项目 → 简单 Spring 实用程序项目,并在提示时按是,然后输入项目和包名称,例如 org.spring.data.cassandra.example

然后,你可以将以下依赖项声明添加到 pom.xml 文件的 dependencies 部分。

<dependencies>

  <dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-cassandra</artifactId>
    <version>{version}</version>
  </dependency>

</dependencies>

此外,你还应该更改 pom.xml 文件中的 Spring 版本如下:

<spring.version>{springVersion}</spring.version>

如果使用里程碑版本而不是 GA 版本,还需要将 Maven 的 Spring Milestone 存储库的位置添加到 pom.xml 文件中,使其与 <dependencies/> 元素处于同一级别,如下所示:

<repositories>
  <repository>
    <id>spring-milestone</id>
    <name>Spring Maven MILESTONE Repository</name>
    <url>https://repo.spring.io/milestone</url>
  </repository>
</repositories>

存储库也是 browseable here

您还可以浏览所有 Spring 存储库 here

现在,您可以创建一个简单的 Java 应用程序来存储和读取 Cassandra 中的域对象。

要执行此操作,首先创建一个简单的域对象类以使其持久化,如下面的示例所示:

/*
 * Copyright 2020-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// tag::file[]
package org.springframework.data.cassandra.example;

import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;

@Table
public class Person {

	@PrimaryKey private final String id;

	private final String name;
	private final int age;

	public Person(String id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public String getId() {
		return id;
	}

	private String getName() {
		return name;
	}

	private int getAge() {
		return age;
	}

	@Override
	public String toString() {
		return String.format("{ @type = %1$s, id = %2$s, name = %3$s, age = %4$d }", getClass().getName(), getId(),
				getName(), getAge());
	}
}
// end::file[]

接下来,创建要运行的主应用程序,如下面的示例所示:

  • Imperative

  • Reactive

/*
 * Copyright 2020-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// tag::file[]
package org.springframework.data.cassandra.example;

import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.cassandra.core.CassandraTemplate;
import org.springframework.data.cassandra.core.query.Criteria;
import org.springframework.data.cassandra.core.query.Query;

import com.datastax.oss.driver.api.core.CqlSession;

public class CassandraApplication {

	private static final Log LOG = LogFactory.getLog(CassandraApplication.class);

	private static Person newPerson(String name, int age) {
		return new Person(UUID.randomUUID().toString(), name, age);
	}

	public static void main(String[] args) {

		CqlSession cqlSession = CqlSession.builder().withKeyspace("mykeyspace").build();

		CassandraOperations template = new CassandraTemplate(cqlSession);

		Person jonDoe = template.insert(newPerson("Jon Doe", 40));

		LOG.info(template.selectOne(Query.query(Criteria.where("id").is(jonDoe.getId())), Person.class).getId());

		template.truncate(Person.class);
		cqlSession.close();
	}

}
// end::file[]
/*
 * Copyright 2020-2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// tag::file[]
package org.springframework.data.cassandra.example;

import reactor.core.publisher.Mono;

import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.cassandra.core.ReactiveCassandraOperations;
import org.springframework.data.cassandra.core.ReactiveCassandraTemplate;
import org.springframework.data.cassandra.core.cql.session.DefaultBridgedReactiveSession;
import org.springframework.data.cassandra.core.query.Criteria;
import org.springframework.data.cassandra.core.query.Query;

import com.datastax.oss.driver.api.core.CqlSession;

public class ReactiveCassandraApplication {

	private static final Log LOG = LogFactory.getLog(ReactiveCassandraApplication.class);

	private static Person newPerson(String name, int age) {
		return new Person(UUID.randomUUID().toString(), name, age);
	}

	public static void main(String[] args) {

		CqlSession cqlSession = CqlSession.builder().withKeyspace("mykeyspace").build();

		 ReactiveCassandraOperations template = new ReactiveCassandraTemplate(new DefaultBridgedReactiveSession(cqlSession));

    Mono<Person> jonDoe = template.insert(newPerson("Jon Doe", 40));

    jonDoe.flatMap(it -> template.selectOne(Query.query(Criteria.where("id").is(it.getId())), Person.class))
				.doOnNext(it -> LOG.info(it.toString()))
        .then(template.truncate(Person.class))
        .block();

		cqlSession.close();
	}

}
// end::file[]

即使在这么简单的例子中,也有一些值得注意的事情:

  • 13. 你可以使用Cassandra`CqlSession`创建`CassandraTemplate`(或`ReactiveCassandraTemplate`用于响应使用)的实例。

  • 14. 你必须将你的POJO注释为Cassandra`@Table`实体,还要注释`@PrimaryKey`。你还可以选择覆盖这些映射名称以匹配Cassandra数据库和列名称。

  • 15. 你可以使用原始CQL或DataStax`QueryBuilder`API来构造你的查询。