Cassandra_Java
Cassandra_Java
Unit test:
<dependency>
<groupId>org.cassandraunit</groupId>
<artifactId>cassandra-unit</artifactId>
<version>4.1.0</version>
</dependency>
Step 2:
In order to connect to Cassandra from Java, we need to build a Cluster object.
@Before
public void connect() {
CassandraConnector client = new CassandraConnector();
client.connect("127.0.0.1", 9142);
this.session = client.getSession();
bookRepository = new BookRepository(session);
}
@Test
public void whenCreatingATable_thenCreatedCorrectly() {
bookRepository.createTable();
ResultSet result = session.execute(
"SELECT * FROM " + KEYSPACE_NAME + ".books;");
List<String> columnNames =
result.getColumnDefinitions().asList().stream()
.map(cl -> cl.getName())
.collect(Collectors.toList());
assertEquals(columnNames.size(), 3);
assertTrue(columnNames.contains("id"));
assertTrue(columnNames.contains("title"));
assertTrue(columnNames.contains("subject"));
}
Step. Altering the Column Family
#Note: A book has also a publisher, but no such column can be found in the
created table. We can use the following code to alter the table and add a new
column:
public void alterTablebooks(String columnName, String columnType) {
StringBuilder sb = new StringBuilder("ALTER TABLE ")
.append(TABLE_NAME).append(" ADD ")
.append(columnName).append(" ")
.append(columnType).append(";");
String query = sb.toString();
session.execute(query);
}
#Let's make sure that the new column publisher has been added:
@Test
public void whenAlteringTable_thenAddedColumnExists() {
bookRepository.createTable();
bookRepository.alterTablebooks("publisher", "text");
ResultSet result = session.execute(
"SELECT * FROM " + KEYSPACE_NAME + "." + "books" + ";");
boolean columnExists = result.getColumnDefinitions().asList().stream()
.anyMatch(cl -> cl.getName().equals("publisher"));
assertTrue(columnExists);
}
A new row has been added in the ‘books' table, so we can test if the row exists:
@Test
public void whenAddingANewBook_thenBookExists() {
bookRepository.createTableBooksByTitle();
In the test code above we have used a different method to create a table
named booksByTitle:
session = builder.build();
}
Step no:3
Create Keyspace
Use the SimpleStrategy replication strategy with the
number of replicas set to 1:
session.execute(createKeyspace.build());
}
// ...
}
//Also, we can start using the keyspace in the current session:
//...