How to connect ScyllaDB with Java

How to connect ScyllaDB with Java

This post gives you Introducing ScyllaDB With Jav, and an overview of ScyllaDB, how to connect with Java using Jakarta EE.

From Wikipedia: "Scylla is an open-source distributed NoSQL data store. It was designed to be compatible with Apache Cassandra while achieving significantly higher throughputs and lower latencies. It supports the same protocols as Cassandra (CQL and Thrift) and the same file formats (SSTable), but is a completely rewritten implementation, using the C++17 language replacing Cassandra's Java, and the Seastar asynchronous programming library replacing threads, shared memory, mapped files, and other classic Linux programming techniques."

This post will test the ScyllaDB with Java and give you the first impression of this database, which is compatible with Apache Cassandra.

Installation

The first step in this tutorial is to install the Scylla database. To make this process easier, we will use Docker, which simplifies a lot of the installation process with just this command:

docker run -d --name scylladb-instance -p 9042:9042 scylladb/scylla

Infrastructure Code

In a Maven project, we need to set the dependency project. Eclipse JNoSQL has two layers: one for mapping and the other one for communication. Once ScyllaDB is compatible with Cassandra, this post will use the Cassandra driver as the dependency for communication. Furthermore, it important to set a CDI implementation.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <artifactId>scylla</artifactId>
  <name>Artemis Demo using Java SE scylla</name>

  <parent>     <groupId>org.jnosql.artemis</groupId>     <artifactId>artemis-demo-java-se</artifactId>     <version>0.0.9</version>   </parent>

  <properties>     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>   </properties>

  <dependencies>

    <dependency>       <groupId>org.jnosql.artemis</groupId>       <artifactId>cassandra-extension</artifactId>       <version>${project.version}</version>     </dependency>   </dependencies>

</project>

Show Me the Code

For this sample, we have the Person entity with idname, and phones as fields:

import org.jnosql.artemis.Column;
import org.jnosql.artemis.Entity;
import org.jnosql.artemis.Id;

import java.util.List;

@Entity("Person") public class Person {

  @Id("id")   private long id;

  @Column   private String name;

  @Column   private List<String> phones;

}

There is a Repository interface that implements the basic operations in the database. Also, it has the method query, which gives the method that Eclipse JNoSQL will implement to the Java developer:

import org.jnosql.artemis.Repository;

public interface PersonRepository extends Repository<Person, Long> {

}

The next step is to make a connection, an entity manager, available to CDI.

import org.jnosql.diana.cassandra.column.CassandraColumnFamilyManager;
import org.jnosql.diana.cassandra.column.CassandraColumnFamilyManagerFactory;
import org.jnosql.diana.cassandra.column.CassandraConfiguration;

import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces;

@ApplicationScoped public class ScyllaProducer {

private static final String KEY_SPACE = "developers";

private CassandraConfiguration cassandraConfiguration;

private CassandraColumnFamilyManagerFactory managerFactory;

@PostConstruct

public void init() {
    cassandraConfiguration = new CassandraConfiguration();
    managerFactory = cassandraConfiguration.get();
}

@Produces
public CassandraColumnFamilyManager getManagerCassandra() {
    return managerFactory.get(KEY_SPACE);
}

}

The ScyllaProducer class makes a manager entity class available and ready for the application use. Once the code does not define the Settings, it will use the default behavior, so it will read from the diana-cassandra.properties file. This file has the configuration startup, thus the port and host to connect. Scylla as Cassandra is not schemaless, which means we need to create the structure before we use it. The properties file has Cassandra Query Language to create the keyspace and the column family structure.

cassandra.host.1=localhost
cassandra.query.1=CREATE KEYSPACE IF NOT EXISTS developers WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};
cassandra.query.2=CREATE COLUMNFAMILY IF NOT EXISTS developers.Person (id bigint PRIMARY KEY, name text, phones list<text>);

The whole configuration process and the code are ready, so let's run the code!

import org.jnosql.artemis.cassandra.column.CassandraTemplate;
import org.jnosql.artemis.column.ColumnTemplate;
import org.jnosql.diana.api.column.ColumnQuery;

import javax.enterprise.inject.se.SeContainer; import javax.enterprise.inject.se.SeContainerInitializer; import java.util.Arrays; import java.util.Optional;

import static org.jnosql.diana.api.column.query.ColumnQueryBuilder.select;

public class App {

public static void main(String[] args) {

    try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {
        Person person = Person.builder().withPhones(Arrays.asList("234", "432"))
                .withName("Ada Lovelace").withId(1).build();
        ColumnTemplate template = container.select(CassandraTemplate.class).get();
        Person saved = template.insert(person);
        System.out.println("Person saved" + saved);

        ColumnQuery query = select().from("Person").where("id").eq(1L).build();

        Optional&lt;Person&gt; result = template.singleResult(query);
        System.out.println("Entity found: " + result);

    }
}

private App() {
}

}

import javax.enterprise.inject.se.SeContainer; import javax.enterprise.inject.se.SeContainerInitializer; import java.util.Arrays; import java.util.Optional;

import static org.jnosql.artemis.DatabaseQualifier.ofColumn;

public class App2 {

public static void main(String[] args) {

    try(SeContainer container = SeContainerInitializer.newInstance().initialize()) {
        Person person = Person.builder().withPhones(Arrays.asList("234", "432"))
                .withName("Ada Lovelace").withId(1).build();
        PersonRepository repository = container.select(PersonRepository.class).select(ofColumn()).get();
        Person saved = repository.save(person);
        System.out.println("Person saved" + saved);

        Optional&lt;Person&gt; result = repository.findById(1L);
        System.out.println("Entity found: " + person);

    }
}

private App2() {}

}

We now have the ability to run a particular behavior in a NoSQL database matter! That's why the Eclipse JNoSQL worries about the extensibility of both Cassandra and ScyllaDB and worries about the support to native query the CQL and operation with consistency level. To support it and move resources, there is the CassandraTemplate, which is an extension of ColumnTemplate and allows features from Cassandra as a consequence on ScyllaDB.

import com.datastax.driver.core.ConsistencyLevel;
import org.jnosql.artemis.cassandra.column.CassandraTemplate;
import org.jnosql.diana.api.column.ColumnQuery;

import javax.enterprise.inject.se.SeContainer; import javax.enterprise.inject.se.SeContainerInitializer; import java.util.Arrays; import java.util.List;

import static org.jnosql.diana.api.column.query.ColumnQueryBuilder.select;

public class App3 {

public static void main(String[] args) {

    try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {
        Person person = Person.builder().withPhones(Arrays.asList("234", "432"))
                .withName("Ada Lovelace").withId(1).build();
        CassandraTemplate cassandraTemplate = container.select(CassandraTemplate.class).get();
        Person saved = cassandraTemplate.save(person, ConsistencyLevel.ONE);
        System.out.println("Person saved" + saved);
        List&lt;Person&gt; people = cassandraTemplate.cql("select * from developers.Person where id = 1");
        System.out.println("Entity found: " + people);

    }
}

private App3() {
}

}

This post gives you an overview of ScyllaDB and how to connect with Java using Jakarta EE. ScyllaDB has compatibility with Cassandra that allows us to use the same Cassandra API without issues. 

Thank you for reading!


Originally published on https://dzone.com

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

How to Build a CRUD API with Java, MongoDB, and Spring Boot

This tutorial shows how to build a CRUD API with Java, MongoDB, and Spring Boot. How to build a CRUD API with Java and MongoDB. In this tutorial, you create a Java data model class and mapped it to a MongoDB domain document using Spring Data annotations. You use a simple embedded MongoDB database as the datastore. You use Spring Boot to quickly and easily expose your data model via a REST API. Finally, you secured the REST API using Okta and Okta’s Spring Boot Starter.

Developing Apps with MongoDB and Java

Want to get started with MongoDB and Java? Developing Apps with MongoDB and Java - Learn how to set up your Java project with Maven and execute a MongoDB command in Java.

Explore MongoDB in a Java application for basic usage.

Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB JDBC driver and Java set up on the machine. You can check Java tutorial for Java installation on your machine.