Close

Cassandra - Mapping Java Objects using Mapper

[Last Updated: Aug 27, 2020]

Cassandra DataStax Java Driver provides a simple object mapper, which avoids manually converting your domain classes to and from query results.

Example

Run Cassandra server and create a keyspace (my_test_keyspace) as described in this tutorial.

Maven dependency

pom.xml

<dependency>
   <groupId>com.datastax.cassandra</groupId>
   <artifactId>cassandra-driver-mapping</artifactId>
   <version>3.10.2</version>
</dependency>

Creating domain class

Cassandra annotations provided in com.datastax.driver.mapping.annotations package are used to map a table to a Java class:

package com.logicbig.example;

import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;

@Table(keyspace = "my_test_keyspace", name = "person")
public class Person {
  @PartitionKey
  private long id;
  private String name;
  private int age;

  public Person() {
  }

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

  public long getId() {
      return id;
  }

  public void setId(long id) {
      this.id = id;
  }

  public String getName() {
      return name;
  }

  public void setName(String name) {
      this.name = name;
  }

  public int getAge() {
      return age;
  }

  public void setAge(int age) {
      this.age = age;
  }

  @Override
  public String toString() {
      return "Person{" +
              "id=" + id +
              ", name='" + name + '\'' +
              ", age=" + age +
              '}';
  }
}

Using Mapper to save/get/delete Java object to/from table

package com.logicbig.example;

import com.datastax.driver.core.*;
import com.datastax.driver.mapping.Mapper;
import com.datastax.driver.mapping.MappingManager;
import java.util.List;

public class CassandraMappingObjectExample {
  public static void main(String[] args) {
      try (Cluster cluster = Cluster.builder()
                                    .addContactPoint("127.0.0.1")
                                    .withPort(9042)
                                    .withoutJMXReporting()
                                    .build()) {
          Session session = cluster.connect("my_test_keyspace");
          session.execute("CREATE TABLE IF NOT EXISTS "
                  + "my_test_keyspace.PERSON (id bigint PRIMARY KEY, name text, age int)");
          MappingManager manager = new MappingManager(session);
          Mapper<Person> mapper = manager.mapper(Person.class);

          //save person
          mapper.save(new Person("Sandy", 33));
          executeNativeSelectQuery(session);

          //getting via mapper by primary key
          Person person = mapper.get(0L);
          System.out.println(person);

          //getting via mapper by primary key
          mapper.delete(0L);//delete by primary key
          executeNativeSelectQuery(session);

          //dropping table at the end
          session.execute("DROP TABLE my_test_keyspace.PERSON");
      }
  }

  private static void executeNativeSelectQuery(Session session) {
      System.out.println("-- select query --");
      ResultSet rs = session.execute("select * from my_test_keyspace.Person");
      List<Row> rows = rs.all();
      System.out.println("rows: " + rows.size());
      for (Row row : rows) {
          long id = row.getLong("id");
          System.out.println("Id: " + id);
          String name = row.getString("name");
          System.out.println("name: " + name);
          int age = row.getInt("age");
          System.out.println("age: " + age);
      }
  }
}
-- select query --
rows: 1
Id: 0
name: Sandy
age: 33
Person{id=0, name='Sandy', age=33}
-- select query --
rows: 0

Primary key, Partition Key and Clustering key

A primary key uniquely identifies a row.

A partition key is used to lookup a partition which is nothing but a set of rows. This is responsible for data distribution across the nodes.

The Primary Key is equivalent to the Partition Key in a single-field-key (not composite key) table.

The Clustering Key is responsible for data sorting within the partition.

Example Project

Dependencies and Technologies Used:

  • cassandra-driver-mapping 3.10.2: Object mapper for the DataStax CQL Java Driver.
  • JDK 8
  • Maven 3.5.4

Cassandra - ObjectMapper Getting Started Select All Download
  • cassandra-java-object-mapper-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Person.java

    See Also