DataStax Java driver

Before using the DataStax driver, review the Best practices for DataStax drivers to understand the rules and recommendations for improving performance and minimizing resource utilization in applications that use a DataStax driver.

If possible, upgrade to the latest native driver.

For more details about supported software, see the DataStax Support Policy.

Upgrade your driver to a compatible version to connect to DataStax 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 DSE Java driver.

Connecting with Java Cloud driver

Prerequisites

Connecting the driver

  1. Add the DataStax Java driver dependency to your pom.xml file, ensuring that the name of the dependncy corresponds to the installed version. For more, review the example pom.xml file. 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>
  1. While running Stargate on Astra DB, create your connection. To connect to your Stargate instance, create the client. For a local Stargate instance, for instance, the following client code will fetch an auth token with a REST call:

    private static final String ASTRA_DB_ID      = "<id>";
    private static final String ASTRA_DB_REGION  = "<region>";
    private static final String ASTRA_TOKEN      = "<token>";
    private static final String ASTRA_KEYSPACE   = "<keyspace>";
    
    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));
  1. 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());
    1. 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.");

Connecting with Java Native driver

Prerequisites

  • Create your database and set your environment variables to save time developing on your database. There are four environment variables, three of which are on the Astra dashboard (database id, region, and keyspace), and one that you must create (token). For more, see Create your database.

  • Download and install Maven.

  • Client ID and Client Secret by creating your application token for your username and password.

Working with secure connect bundle

This page explains how to use the secure connect bundle for Astra DB Classic.

If you want to use the secure connect bundle with Astra DB Serverless, see the Astra DB Serverless documentation.

Downloading secure connect bundle

To get the necessary security credentials and certificates for connecting drivers to your Astra DB database, you’ll need to download the secure connect bundle from the DataStax Astra Portal.

  1. Open your Astra Portal and select your database.

  2. On the Overview page, select Connect.

  3. In the Database Essentials section, click Get Bundle.

  4. In the Secure Connect Bundle Download dialog box, use the Select a region dropdown menu to select the region for which you want to download the bundle. If you have multiple regions, you can download a bundle for each region.

    If you’ve enabled VPC peering, you can also Download External Secure Connect Bundle for use within your VPC peering. VPC peering is only available on Classic databases.

  5. After selecting a region, various options for downloading the bundle appear. To download the bundle to your local computer, click Download Secure Bundle.

    The secure connect bundle downloads as a ZIP file named secure-connect-<database_name>.zip.

    Expiration of download link

    For added security, the download link for the secure connect bundle expires after five minutes. Once the download link expires, you’ll need to repeat the steps above to regenerate a new download link.

    Note that the secure connect bundle itself never expires.

Sharing secure connect bundle

Although teammates can access your Astra DB database, it doesn’t display in their list of available databases under My Databases in Astra Portal.

After you create an Astra DB database, you can grant access to other members of your team by providing them with the database credentials and connection details for your database.

Be careful when sharing connection details. Providing this information to another user grants them access to your Astra DB database and ownership capabilities, such as making modifications to the database.

For security, delete downloaded connection credentials after sending them to your teammate.

Secure connect bundle contents

The Secure Connect Bundle (SCB) contains the following files:

File Contents

ca.crt

DataStax’s Certificate Authority public certificate

cert

A certificate, unique to the specific SCB

key

A private key, unique to the specific SCB

cert.pfx

A PFX formatted archive containing the certificate and the private key

config.json

A configuration file with information on how to securely connect to the Astra DB instance associated with the SCB

cqlshrc

A CQLSH profile containing CQL shell session settings

identity.jks

A Java keystore file containing the aforementioned cert & key files

trustStore.jks

A Java keystore file containing the aforementioned ca.crt

Connecting the driver

  1. Navigate to the pom.xml file at the root of your Java project and open it for editing.

    For a complete pom.xml file, see the example pom.xml file below.

  1. Add the DataStax Java driver dependency to your pom.xml file with the latest version Maven Central.

    <!--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_4X_VERSION</version>
    </dependency>
  1. Save and close your pom.xml file.

  2. Initialize the DataStax Java driver.

  3. Create a ConnectDatabase.java file in the /src/main/java directory for your Java project.

    mkdir javaProject
    cd javaProject
    mkdir -p src/main/java
    touch src/main/java/ConnectDatabase.java
  1. Copy the following code for your DataStax driver into the ConnectDatabase.java file. The following example implements a ConnectDatabase class to connect to your Astra DB database, runs a CQL query, and 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/secure-connect-DATABASE_NAME.zip"))
               .withAuthCredentials("clientId","clientSecret")
               .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);
       }
    }
  1. Make the following changes:

    • Use the withCloudSecureConnectBundle() method to specify the path to the secure connect bundle for your Astra DB database.

    • Use the withAuthCredentials() method to specify the username and password for your database.

    • Use the withKeyspace() method to specify the keyspace name for your database.

  1. Save and close the ConnectDatabase.java file.

Example pom.xml file

You can use the following pom.xml file in your Java project to connect to your Astra DB database. If you already have a pom.xml file for your Java project, copy only the repository and dependencies as indicated in the previous steps.

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>JAVA_DRIVER_VERSION</java.driver.version>
    </properties>
    <dependencies>
        <!-- START-javaDriverDependencyCore -->
        <dependency>
            <groupId>com.datastax.oss</groupId>
            <artifactId>java-driver-core</artifactId>
            <version>$JAVA_DRIVER_VERSION</version>
        </dependency>
        <!-- END-javaDriverDependencyCore -->
        <!-- START-javaDriverDependencyQuery -->
        <dependency>
            <groupId>com.datastax.oss</groupId>
            <artifactId>java-driver-query-builder</artifactId>
            <version>$JAVA_DRIVER_VERSION</version>
        </dependency>
        <!-- END-javaDriverDependencyQuery -->
        <!-- START-javaDriverDependencyMapper -->
        <dependency>
            <groupId>com.datastax.oss</groupId>
            <artifactId>java-driver-mapper-runtime</artifactId>
            <version>$JAVA_DRIVER_VERSION</version>
        </dependency>
        <!-- END-javaDriverDependencyMapper -->
    </dependencies>
</project>

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