DataStax Java driver

Before using a DataStax driver, review Best practices for DataStax drivers and upgrade or install the latest supported driver for your language. For more details about supported software, see the DataStax Support Policy.

Upgrade your driver to a compatible version to connect to Astra DB databases. For more information, see the DataStax Driver Matrix.

You add a repository and dependencies to the pom.xml file for your project to download the appropriate .jar files for the Java driver and make them available to your code. Additionally, you implement a ConnectDatabase class to initialize the Java driver.

Connect the Java driver

  1. Create a database, and then set environment variables for database ID, region, and keyspace.

  2. Create an application token, and then set a token environment variable.

    The token.json has the following format:

    {
      "clientId": "CLIENT_ID",
      "secret": "CLIENT_SECRET",
      "token": "APPLICATION_TOKEN"
    }

    For authentication with the driver, you can use either clientId and secret or the literal string token and the AstraCS token value. If you are on an older driver version that doesn’t support token and AstraCS, then you might need to use clientId and secret.

  3. Download your database’s Secure Connect Bundle (SCB).

  4. Install Maven.

  5. Add the latest DataStax Java driver Maven Central dependency to your project’s pom.xml file:

    <!--Use the latest version from https://search.maven.org/artifact/com.datastax.oss/java-driver-core -->
    <dependency>
      <groupId>com.datastax.oss</groupId>
      <artifactId>java-driver-core</artifactId>
      <version>LATEST_VERSION</version>
    </dependency>
    Example pom.xml

    The following pom.xml file includes DataStax Java driver dependencies. If you already have a pom.xml file for your Java project, you only need the Java driver repository and dependencies.

    Replace VERSION with the current Java driver version Maven Central.

    <?xml version="1.0" encoding="UTF-8"?>
    <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/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>net.techne.web</groupId>
        <artifactId>cloudTest</artifactId>
        <version>1.0</version>
        <packaging>jar</packaging>
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
            <!--Use the latest version from https://search.maven.org/artifact/com.datastax.oss/java-driver-core -->
            <java.driver.version>VERSION</java.driver.version>
        </properties>
        <dependencies>
            <!-- START-javaDriverDependencyCore -->
            <dependency>
                <groupId>com.datastax.oss</groupId>
                <artifactId>java-driver-core</artifactId>
                <version>$VERSION</version>
            </dependency>
            <!-- END-javaDriverDependencyCore -->
            <!-- START-javaDriverDependencyQuery -->
            <dependency>
                <groupId>com.datastax.oss</groupId>
                <artifactId>java-driver-query-builder</artifactId>
                <version>$VERSION</version>
            </dependency>
            <!-- END-javaDriverDependencyQuery -->
            <!-- START-javaDriverDependencyMapper -->
            <dependency>
                <groupId>com.datastax.oss</groupId>
                <artifactId>java-driver-mapper-runtime</artifactId>
                <version>$VERSION</version>
            </dependency>
            <!-- END-javaDriverDependencyMapper -->
        </dependencies>
    </project>
  6. Save and close your pom.xml file.

  7. Create a ConnectDatabase.java file in your Java project’s /src/main/java directory:

    cd JAVA_PROJECT_DIRECTORY/src/main/java
    touch ConnectDatabase.java
  8. Enter the following code in the ConnectDatabase.java file. This code imports dependencies, initializes the Java driver, implements a ConnectDatabase class to connect to your Astra DB database, runs a CQL query, and then prints the output to the console.

    import com.datastax.oss.driver.api.core.CqlSession;
    import com.datastax.oss.driver.api.core.cql.ResultSet;
    import com.datastax.oss.driver.api.core.cql.Row;
    import java.nio.file.Paths;
    
    public class ConnectDatabase {
    
       public static void main(String[] args) {
           // Create the CqlSession object:
           try (CqlSession session = CqlSession.builder()
               .withCloudSecureConnectBundle(Paths.get("PATH_TO_SCB"))
               .withAuthCredentials("CLIENT_ID","CLIENT_SECRET")
               .withKeyspace("KEYSPACE_NAME")
               .build()) {
               // Select the release_version from the system.local table:
               ResultSet rs = session.execute("select release_version from system.local");
               Row row = rs.one();
               //Print the results of the CQL query to the console:
               if (row != null) {
                   System.out.println(row.getString("release_version"));
               } else {
                   System.out.println("An error occurred.");
               }
           }
           System.exit(0);
       }
    }

    Replace the following:

    • PATH_TO_SCB: The path to your database’s downloaded Secure Connect Bundle (SCB) zip file.

    • CLIENT_ID and CLIENT_SECRET: Provide Astra DB authentication credentials. This can be either the clientId and secret or the literal string token and an AstraCS token value.

    • KEYSPACE_NAME: The name of a keyspace in your database.

  9. Save ConnectDatabase.java and then build your Maven project.

Connect the Java Cloud driver (deprecated)

The legacy Stargate APIs and their associated drivers are deprecated for Astra DB Classic as of September 2024, and end-of-life (EOL) is scheduled for the end of 2025. As EOL approaches, DataStax will provide migration information to support your transition to other options.

If you have questions or concerns, contact your account representative or DataStax Support.

  1. Generate a Bearer Token and select Database Administrator for the role.

  2. Install a Java Development Kit (SDK) and Maven.

  3. Create a keyspace.

  4. Create a table for your keyspace.

  5. Add the Java Cloud driver dependencies to your pom.xml file. Make sure the dependency names correspond to the installed versions.

    Replace PROTO_VERSION with the current gRPC proto version Maven Central, and replace NETTY_VERSION with the current gRPC netty version Maven Central.

    <dependencies>
      <dependency>
        <groupId>io.stargate.grpc</groupId>
        <artifactId>grpc-proto</artifactId>
        <version>PROTO_VERSION</version>
      </dependency>
      <dependency>
        <groupId>io.grpc</groupId>
        <artifactId>grpc-netty-shaded</artifactId>
        <version>NETTY_VERSION</version>
      </dependency>
    </dependencies>
  6. While running Stargate on Astra DB, create a connection. To connect to your Stargate instance, create the client. For example, for a local Stargate instance, the following client code fetches an authentication token with a REST call:

    private static final String ASTRA_DB_ID      = "DATABASE_ID";
    private static final String ASTRA_DB_REGION  = "REGION_NAME";
    private static final String ASTRA_TOKEN      = "APPLICATION_TOKEN";
    private static final String ASTRA_KEYSPACE   = "KEYSPACE_NAME";
    
    public static void main(String[] args)
    throws Exception {
      //-------------------------------------
      // 1. Initializing Connectivity
      //-------------------------------------
      ManagedChannel channel = ManagedChannelBuilder
              .forAddress(ASTRA_DB_ID + "-" + ASTRA_DB_REGION + ".apps.astra.datastax.com", 443)
              .useTransportSecurity()
              .build();
    
      // blocking stub version
      StargateGrpc.StargateBlockingStub blockingStub =
          StargateGrpc.newBlockingStub(channel)
              .withDeadlineAfter(10, TimeUnit.SECONDS)
              .withCallCredentials(new StargateBearerToken(ASTRA_TOKEN));
    }
  7. Perform a query by passing a CQL query to the client using the ExecuteQuery() function for standard query execution:

    QueryOuterClass.Response queryString = blockingStub.executeQuery(QueryOuterClass
      .Query.newBuilder()
      .setCql("SELECT firstname, lastname FROM " + ASTRA_KEYSPACE + ".users")
      .build());
  8. To use a batch statement, provide an ExecuteBatch() function to execute a batch query:

    blockingStub.executeBatch(
      QueryOuterClass.Batch.newBuilder()
          .addQueries(
              QueryOuterClass.BatchQuery.newBuilder()
                  .setCql("INSERT INTO " + ASTRA_KEYSPACE + ".users (firstname, lastname) VALUES('Jane', 'Doe')")
                  .build())
          .addQueries(
              QueryOuterClass.BatchQuery.newBuilder()
                  .setCql("INSERT INTO " + ASTRA_KEYSPACE + ".users (firstname, lastname) VALUES('Serge', 'Provencio')")
                  .build())
          .build());
    System.out.println("2 rows have been inserted in table users.");

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2024 DataStax | Privacy policy | Terms of use

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: +1 (650) 389-6000, info@datastax.com