1. maven 依赖
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-cql</artifactId>
</dependency>
2. 创建 Cassandra keysapce,表定义
CREATE KEYSPACE dalong WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
CREATE TABLE userapp(user_id text PRIMARY KEY ,firstname text ,lastname text );
3. 实体映射定义
package com.yonyou.op.Enties;
import java.io.Serializable;
import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;
@Table(value = "userapp")
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
@PrimaryKey
private String user_id;
private String firstname;
private String lastname;
public Person() {
// TODO Auto-generated constructor stub
}
public Person(String id, String name, String age) {
this.user_id = id;
this.firstname = name;
this.lastname = age;
}
public String getUser_id() {
return user_id;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
@Override
public String toString() {
return "Person [user_id=" + user_id + ", firstname=" + firstname
+ ", lastname=" + lastname + "]";
}
}
4. 添加,查询代码
public class Appdemo2 {
private static final Logger LOGGER = LoggerFactory
.getLogger(Appdemo2.class);
protected static Person newPerson(String name, String age) {
return newPerson(UUID.randomUUID().toString(), name, age);
}
protected static Person newPerson(String id, String name, String age) {
return new Person(id, name, age);
}
public static void main(String[] args) {
Cluster cluster = Cluster.builder().addContactPoints("XXXXXX")
.build();
Session session = cluster.connect("dalong");
CassandraOperations template = new CassandraTemplate(session);
Person jonDoe = template.insert(newPerson("Jon Doe", "dddd"));
Select selectStatement = QueryBuilder.select()
.from("dalong", "userapp");
selectStatement.allowFiltering();
selectStatement
.where(QueryBuilder.eq("lastname", jonDoe.getLastname()));
List<Person> selectpersons = template.select(selectStatement,
Person.class);
for (Person p : selectpersons) {
LOGGER.info(p.toString());
}
session.close();
cluster.close();
}
}
5. 常见问题:
a. spring data Cassandra 版本问题,目前已经支持3.0 但是需要使用新版本的spring
不然会出现比较怪异的问题