1. maven  依赖

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