• Glossary
  • Support
  • Downloads
  • DataStax Home
Get Live Help
Expand All
Collapse All

DataStax Astra DB Classic Documentation

    • Overview
      • Release notes
      • Astra DB FAQs
      • Astra DB glossary
      • Get support
    • Getting Started
      • Grant a user access
      • Load and retrieve data
        • Use DSBulk to load data
        • Use Data Loader in Astra Portal
      • Connect a driver
      • Build sample apps
      • Use integrations
        • Connect with DataGrip
        • Connect with DBSchema
        • Connect with JanusGraph
        • Connect with Strapi
    • Planning
      • Plan options
      • Database regions
    • Securing
      • Security highlights
      • Security guidelines
      • Default user permissions
      • Change your password
      • Reset your password
      • Authentication and Authorization
      • Astra DB Plugin for HashiCorp Vault
    • Connecting
      • Connecting to a VPC
      • Connecting Change Data Capture (CDC)
      • Connecting CQL console
      • Connect the Spark Cassandra Connector to Astra
      • Drivers for Astra DB
        • Connecting C++ driver
        • Connecting C# driver
        • Connecting Java driver
        • Connecting Node.js driver
        • Connecting Python driver
        • Drivers retry policies
      • Connecting Legacy drivers
      • Get Secure Connect Bundle
    • Migrating
      • FAQs
      • Preliminary steps
        • Feasibility checks
        • Deployment and infrastructure considerations
        • Create target environment for migration
        • Understand rollback options
      • Phase 1: Deploy ZDM Proxy and connect client applications
        • Set up the ZDM Automation with ZDM Utility
        • Deploy the ZDM Proxy and monitoring
          • Configure Transport Layer Security
        • Connect client applications to ZDM Proxy
        • Manage your ZDM Proxy instances
      • Phase 2: Migrate and validate data
      • Phase 3: Enable asynchronous dual reads
      • Phase 4: Change read routing to Target
      • Phase 5: Connect client applications directly to Target
      • Additional resources
        • Glossary
        • Troubleshooting
          • Troubleshooting tips
          • Troubleshooting scenarios
        • Contribution guidelines
        • Release Notes
    • Managing
      • Managing your organization
        • User permissions
        • Pricing and billing
        • Audit Logs
        • Configuring SSO
          • Configure SSO for Microsoft Azure AD
          • Configure SSO for Okta
          • Configure SSO for OneLogin
      • Managing your database
        • Create your database
        • View your databases
        • Database statuses
        • Use DSBulk to load data
        • Use Data Loader in Astra Portal
        • Monitor your databases
        • Manage multiple keyspaces
        • Using multiple regions
        • Terminate your database
        • Resize your classic database
        • Park your classic database
        • Unpark your classic database
      • Managing with DevOps API
        • Managing database lifecycle
        • Managing roles
        • Managing users
        • Managing tokens
        • Managing multiple regions
        • Get private endpoints
        • AWS PrivateLink
        • Azure PrivateLink
        • GCP Private Service
    • Astra CLI
    • Developing with Stargate APIs
      • Develop with REST
      • Develop with Document
      • Develop with GraphQL
        • Develop with GraphQL (CQL-first)
        • Develop with GraphQL (Schema-first)
      • Develop with gRPC
        • gRPC Rust client
        • gRPC Go client
        • gRPC Node.js client
        • gRPC Java client
      • Develop with CQL
      • Tooling Resources
      • Node.js Document API client
      • Node.js REST API client
    • Stargate QuickStarts
      • Document API QuickStart
      • REST API QuickStart
      • GraphQL API CQL-first QuickStart
    • API References
      • DevOps REST API v2
      • Stargate Document API v2
      • Stargate REST API v2
  • DataStax Astra DB Classic Documentation
  • Connecting
  • Drivers for Astra DB
  • Connecting Java driver

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.

DataStax recommends using the unified DataStax driver. See this blog post for more information. You can also use the DataStax Enterprise (DSE) drivers, which exposes the same API for connecting to Cassandra databases.

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-native driver

Prerequisites

  • Generate a Bearer Token and select API Administrator User for the role.

  • Create a keyspace

  • Create a table for your keyspace (optional): REST

  • Ensure a Java Development Kit (SDK) and Apache Maven are installed.

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.

    <dependencies>
      <dependency>
        <groupId>io.stargate.grpc</groupId>
        <artifactId>grpc-proto</artifactId>
        <version>1.0.41</version>
      </dependency>
      <dependency>
        <groupId>io.grpc</groupId>
        <artifactId>grpc-netty-shaded</artifactId>
        <version>1.41.0</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 legacy 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

Downloading secure connect bundle

To connect to your Astra DB database using the drivers, download the secure database bundle from the DataStax Astra Portal that contains the connection credentials.

  1. Open a browser, navigate to Astra DB, and log in.

  1. From your Dashboard page, select your database.

  1. On the Overview page, select Connect.

  1. In the Select a Method section, select Drivers and then Legacy from the dropdown menu to select your driver type from the list to load language-specific instructions.

    Java and Node.js are available as legacy and cloud native drivers.

    If you have multiple regions, select the region you want to connect to from the dropdown menu for instructions.

    The bundle URL is the same for all languages.

  1. Click Download Bundle.

    If you have multiple regions, you will have the option to download a bundle for each region from the expanded Download Bundle drop-down menu.

If you’ve enabled VPC peering, you can also Download External Secure Connect Bundle for use within your VPC peering.

The secure-connect-database_name.zip file downloads, which contains the security certificates and credentials for your database.

VPC peering is only available on Classic databases.

Sharing secure connect bundle

Although teammates can access your Astra DB database, it will not 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.

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, ensuring that the name of the dependency corresponds to the installed version: This dependency causes Maven to automatically download the appropriate .jar files found at the url specified in the repository for the DSE Java driver and make them available to your code.

    <!--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>4.14.1</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.

    cd **javaProject**/src/main/java
    touch 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.

<?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>4.14.1</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>

Migrating Java driver

Complete the following procedure to migrate your existing DataStax Java driver to a version capable of connecting to Astra DB databases created using DataStax Astra DB.

  1. In your existing DSE Java driver code, update dependencies to include the DSE Java driver version that can connect to Astra DB databases.

    • DataStax Java driver for Apache Cassandra 4.x

    • DataStax Java driver for Apache Cassandra 3.x

    • DSE Java 2.x

    • DSE Java 1.x

    <dependency>
      <groupId>com.datastax.oss</groupId>
      <artifactId>java-driver-core</artifactId>
      <!--Use the latest version from https://search.maven.org/artifact/com.datastax.oss/java-driver-core -->
      <version>4.14.1</version>
    </dependency>
    <dependency>
      <groupId>com.datastax.cassandra</groupId>
      <artifactId>cassandra-driver-core</artifactId>
      <!--Use the latest version from https://search.maven.org/artifact/com.datastax.cassandra/cassandra-driver-core -->
      <version>3.11.2</version>
    </dependency>
    ----
    <dependency>
      <groupId>com.datastax.dse</groupId>
      <artifactId>dse-java-driver-core</artifactId>
      <!--Use the latest version from https://search.maven.org/artifact/com.datastax.dse/dse-java-driver-core -->
      <version>2.4.0</version>
    </dependency>
    ----
    <dependency>
      <groupId>com.datastax.dse</groupId>
      <artifactId>dse-java-driver-core</artifactId>
      <!-- Use the latest 1.x version from https://search.maven.org/artifact/com.datastax.dse/dse-java-driver-core -->
      <version>1.9.0</version>
    </dependency>
  1. Optional: To use DSE QueryBuilder, which is a utility used to generate CQL queries programmatically, add the following dependency to your pom.xml file:

<dependency>
  <groupId>com.datastax.dse</groupId>
  <artifactId>dse-java-driver-query-builder</artifactId>
  <!-- Use the latest 4.x version from https://search.maven.org/artifact/com.datastax.oss/java-driver-query-builder -->
  <version>4.14.1</version>
</dependency>
  1. Modify the connection code to use the Astra DB API. In the CqlSession or Session objects (DseCluster or DseSession objects for DSE), include the path to the secure connect bundle for your Cassandra database (secure-connect-database_name.zip) in the withCloudSecureConnectBundle() method, as shown in the following example.

    • DataStax Java driver for Apache Cassandra 4.x

    • DataStax Java driver for Apache Cassandra 3.x

    • Java 2.x

    • Java 1.x

    CqlSession session = CqlSession.builder()
      .withCloudSecureConnectBundle("/path/to/secure-connect-database_name.zip")
      .withAuthCredentials("clientId","clientSecret")
      .withKeyspace("keyspace_name")
      .build())
    Session session = Cluster.builder()
      .withCloudSecureConnectBundle("/path/to/secure-connect-database_name.zip")
      .withAuthProvider(new PlainTextAuthProvider("clientId", "clientSecret"))
      .build()
      .connect("keyspace_name"))
    DseSession session = DseSession.builder()
      .withCloudSecureConnectBundle("/path/to/secure-connect-database_name.zip")
      .withAuthCredentials("clientId", "clientSecret")
      .withKeyspace("keyspace_name")
      .build();
    DseCluster cluster = DseCluster.builder()
      .withCloudSecureConnectBundle("/path/to/secure-connect-database_name.zip")
      .withCredentials("clientId", "clientSecret")
      .build();
    DseSession session = cluster.connect("keyspace_name");

If converting from using the open source Cassandra Java driver to the DSE Java driver, ensure that you change Session to DseSession.

  1. Build the project to test the connection.

mvn clean compile exec:java -Dexec.mainClass=YourJavaDriver.java

If successful, the code builds, compiles, and connects to your Cassandra database.

Connecting C# driver Connecting Node.js driver

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

© DataStax | Privacy policy | Terms of use

DataStax, Titan, and TitanDB are registered trademarks of DataStax, Inc. and its subsidiaries in the United States and/or other countries.

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.

landing_page landingpage