Un mémo lorsque j'ai essayé de couper et coller l'exemple de code dans Official DataStax Manual ..
Installez 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
Démarrez le serveur Cassandra
$ /opt/cassandra/bin/cassandra
Créez un espace clé (nom: ks
)
$ /opt/cassandra/bin/cqlsh 127.0.0.1 -e "\
CREATE KEYSPACE ks\
WITH REPLICATION = { 'class': 'SimpleStrategy', 'replication_factor': 1 };"
Créer une table (nom: ʻ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
Ajouter des dépendances pour cassandra-driver-core
et 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>
...
```
Code source
Classe mappée
```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;
}
}
```
--Classe principale
```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();
}
}
}
}
```
Après avoir exécuté la classe principale ci-dessus, vérifiez à partir de cqlsh si des données ont été insérées.
$ /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