Cassandra の Java 向け Object Mapper を触ってみた

# Cassandra の Java 向け Object Mapper を触ってみた
[DataStax の公式のマニュアル](https://github.com/datastax/java-driver/blob/3.x/manual/object_mapper)に載っているサンプルコードを、ぺたぺた切り貼りして動かしてみたときのメモ。

## 前提
- Ubuntu 17.04
- Cassandra 3.10
- Java 側の Cassandra Driver 3.2.0

## 準備
### Cassandra 側
1. Cassandra のインストール

    ```bash
    $ wget http://ftp.jaist.ac.jp/pub/apache/cassandra/3.10/apache-cassandra-3.10-bin.tar.gz
    $ tar -zxvf apache-cassandra-3.10-bin.tar.gz
    $ sudo mv apache-cassandra-3.10/ /opt/cassandra
    ```

1. Cassandra サーバの起動

    ```bash
    $ /opt/cassandra/bin/cassandra
    ```

1. Keyspace の作成（名前: `ks`）

    ```bash
    $ /opt/cassandra/bin/cqlsh 127.0.0.1 -e "\
    CREATE KEYSPACE ks\
      WITH REPLICATION = { 'class': 'SimpleStrategy', 'replication_factor': 1 };"
    ```

1. Table の作成（名前: `users`）

    ```bash
    $ /opt/cassandra/bin/cqlsh 127.0.0.1 -e "\
    CREATE TABLE ks.users (\
      user_id uuid,\
      name text,\
      strength int,\
      PRIMARY KEY(user_id, name)\
    );"
    ```

### Java 側

- pom.xml
    - `cassandra-driver-core` と `cassandra-driver-mapping` の依存を追加する

        ```xml:pom.xml
        ...
        <dependency>
            <groupId>com.datastax.cassandra</groupId>
            <artifactId>cassandra-driver-core</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.datastax.cassandra</groupId>
            <artifactId>cassandra-driver-mapping</artifactId>
            <version>3.2.0</version>
        </dependency>
        ...
        ```

- ソースコード
    - マッピング対象のクラス

        ```User.java
        package sample;
        
        import com.datastax.driver.mapping.annotations.ClusteringColumn;
        import com.datastax.driver.mapping.annotations.Column;
        import com.datastax.driver.mapping.annotations.Param;
        import com.datastax.driver.mapping.annotations.PartitionKey;
        import com.datastax.driver.mapping.annotations.Table;
        import java.util.UUID;
        
        @Table(keyspace = "ks", name = "users",
            readConsistency = "QUORUM",
            writeConsistency = "QUORUM",
            caseSensitiveKeyspace = false,
            caseSensitiveTable = false)
        public class User {
        
          @PartitionKey
          @Column(name = "user_id")
          private UUID userId;
        
          @ClusteringColumn
          private String name;
        
          private int strength;
        
        
          public User(UUID userId, String name, int strength) {
            this.userId = userId;
            this.name = name;
            this.strength = strength;
          }
        }
        ```

    - メインクラス

        ```Main.java
        package sample;

        import com.datastax.driver.core.Cluster;
        import com.datastax.driver.core.Session;
        import com.datastax.driver.mapping.Mapper;
        import com.datastax.driver.mapping.MappingManager;
        import java.util.UUID;

        public class Main {

          public static void main(String[] args) {
            Cluster cluster = null;
            try {
              cluster = Cluster.builder()
                  .addContactPoint("127.0.0.1")
                  .build();
              Session session = cluster.connect();
              MappingManager manager = new MappingManager(session);
              Mapper<User> mapper = manager.mapper(User.class);

              User u = new User(UUID.randomUUID(), "John Doe", 9999);
              mapper.save(u);

            } finally {
              if (cluster != null) {
                cluster.close();
              }
            }
          }
        }
        ```

## 実行結果

上記のメインクラス実行後、データが挿入されたかどうかを cqlsh から確認してみる。

```bash
$ /opt/cassandra/bin/cqlsh 127.0.0.1 -e "SELECT * FROM ks.users;"

 user_id                              | name     | strength
--------------------------------------+----------+----------
 e918961b-57c1-4f5d-8c4e-9d08e9ea4e7a | John Doe |     9999

(1 rows)
```

## 参考
- https://github.com/datastax/java-driver/blob/3.x/manual/README.md
- https://github.com/datastax/java-driver/blob/3.x/manual/object_mapper