A memo when I cut and pasted the sample code in Official DataStax Manual and moved it. ..
Install Cassandra
$ 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
Start Cassandra server
$ /opt/cassandra/bin/cassandra
Create Keyspace (name: ks
)
$ /opt/cassandra/bin/cqlsh 127.0.0.1 -e "\
CREATE KEYSPACE ks\
WITH REPLICATION = { 'class': 'SimpleStrategy', 'replication_factor': 1 };"
Create Table (name: ʻusers`)
$ /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)\
);"
pom.xml
--Add dependencies for cassandra-driver-core
and 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>
...
```
Source code --Mapped class
```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 class
```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();
}
}
}
}
```
After executing the above main class, check from cqlsh whether data has been inserted.
$ /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)
Recommended Posts