Get started with the Java driver
Because Astra Managed Clusters is based on Apache Cassandra®, you can use Cassandra drivers to connect to your Astra databases.
This quickstart explains how to install a driver, connect it to your Astra database, and then send some CQL statements to the database.
To use the Java driver, you need to choose a compatible version, add the driver dependency to your pom.xml, use the ConnectDatabase class to initialize the driver, and then connect the driver to your Astra database.
Once connected, you can write scripts that use the driver to run commands against your database.
Java driver ownership, groupId, and artifact naming conventions
Starting with versions 4.18 and 3.12, the Java driver is maintained by the Apache Software Foundation (ASF). Prior versions were maintained by DataStax.
In version 4.18 and later, the groupId is org.apache.cassandra.
This is a breaking change from earlier versions that used com.datastax.cassandra.
Make sure you update this value in your Java project dependencies.
For examples, see Add the Java driver dependency.
DataStax recommends that you upgrade to the 4.x series if you are on any earlier version.
When upgrading from the 3.x series, be aware that the artifact naming convention for the 4.x series is java-driver-*, not cassandra-driver-*.
Java driver compatibility
DataStax officially supports the latest 12 months of releases, and DataStax recommends using the latest driver version whenever possible. Compatibility isn’t guaranteed for earlier versions. For upgrade guides and compatibility information for earlier versions, see Unsupported drivers.
New features and bug fixes are developed on the latest minor version of the driver, and users are encouraged to stay current with those minor releases. APIs are maintained stable according to semantic versioning conventions, and upgrades should be trivial.
Unless otherwise specified, compatibility version ranges include all patch versions. For example, a range of 4.0 to 4.3 includes all versions from 4.0.0 to the last 4.3.z release.
| Driver version | Astra compatibility | Comments |
|---|---|---|
Fully compatible |
||
4.19.1 |
Partially compatible |
A known issue in version 4.19.1 can cause some requests to Astra DB to fail. This issue is fixed in version 4.19.2 and later. |
4.16 to 4.19.0 |
Fully compatible |
Starting with version 4.18, this driver is maintained by the Apache Software Foundation (ASF). |
4.3 to 4.15 |
Partially compatible |
Doesn’t support the vector type. |
4.0 to 4.2 |
Not compatible |
For Java driver 3.x series compatibility, see Unsupported drivers.
Prepare the environment and database
-
Install a Java version that is compatible with your preferred Java driver version. For more information, see the Java driver documentation.
-
Install Apache Maven™ (or similar).
-
Download your database’s Secure Connect Bundle (SCB).
For more information, including connections to multi-region databases, see The SCB and encrypted connections for drivers.
-
Set the following environment variables:
-
DATABASE_ID: The database ID. -
APPLICATION_TOKEN: An application token with the Database Administrator role.For more information, see Authentication methods for drivers.
-
Authentication methods for drivers
You use an application token and a Secure Connect Bundle (SCB) to connect a driver to an Astra database.
The application token authenticates the driver to the database, and the token’s role determines the actions that the driver is authorized to perform on the database.
When you generate a token, the token details include a clientId, secret, and token:
{
"clientId": "CLIENT_ID",
"secret": "CLIENT_SECRET",
"token": "APPLICATION_TOKEN"
}
-
clientIdandsecretare legacy authentication methods that predatetoken. -
tokenis a unified token that comprises everything you need for Astra token authentication.
Cassandra drivers use username and password authentication for Astra connections, typically through an authentication class or argument, such as PlainTextAuthProvider.
To set the username and password for a Cassandra driver connection, you can use either the unified token or the legacy clientId and secret:
- Unified
tokenauthentication (Recommended) -
To authenticate with the unified application token, set the username to the literal string
token, and set the password to your unified application token. For example:("token", "APPLICATION_TOKEN") - Legacy
clientIdandsecretauthentication -
For legacy applications and older driver versions that don’t use unified application tokens, you can use the
clientIdas the username and thesecretas the password. For example:("CLIENT_ID", "SECRET")However, if you are using a legacy token created prior to the introduction of the unified
tokenformat, DataStax recommends rotating these tokens due to their age.
In addition to the application token, you must provide an SCB to set contact points and establish a secure connection to your database. For more information, see The SCB and encrypted connections for drivers.
The SCB and encrypted connections for drivers
In addition to an application token, you must provide an SCB to set contact points and provide certificates necessary to establish a secure mutual TLS (mTLS) connection to your database.
To establish an encrypted connection between your application and database, the driver uses the SSL certificates and trusted certificate authorities (CAs) in the SCB to verify the Astra server’s identity. Mechanically, when the driver receives the server’s SSL certificate during the SSL handshake, it checks that the certificate was signed by one of the registered CAs. If the certificate wasn’t signed by a registered CA, the driver checks that the signer was signed by one of the registered CAs. It continues through the signers until it finds one that is in the list of trusted CAs. If there are no matches, then identity verification fails and the driver connection isn’t established.
All Astra-compatible drivers have configuration file attributes, builder methods, or constructor parameters to use the SCB. In your driver configuration, you set the path to the SCB zip file, and then the driver automatically gets the required information and files from the SCB. When using an SCB, don’t set any options that are inferred from the SCB, such as contact points and SSL encryption settings. Additionally, don’t extract the SCB zip file; it must be provided to the driver as an unextracted archive.
For multi-region databases, you need the region-specific SCB for each region that your application will connect to.
To connect to one region of a multi-region database, download the SCB for a region that is geographically close to your application to reduce latency.
To connect to multiple regions or databases in the same application, download the SCB for each region or database.
Then, in your application’s code, create one root driver instance (session or cluster) for each region or database, using custom logic to select the appropriate SCB for each instance.
For more information, see Best practices: Session and cluster handling and Connection pools and initial contact points.
DataStax recommends that you use a driver version that supports SCB authentication for simplified configuration and reduced chance of connection failures.
However, if you must support a legacy application with an earlier driver, you can use cql-proxy, extract the SCB, and then manually provide the required certificates to the driver.
Additionally, you must use the token’s clientId and secret for the username and password, respectively.
For an example, see DataStax Ruby and PHP drivers (Maintenance).
Add the Java driver dependency
In your project’s pom.xml file, add a dependency for the Apache Cassandra Java driver :
|
If you install an earlier version of the driver, make sure your version is compatible with Astra and your application’s CQL statements. For example, if you need to query vector data, make sure your driver version supports the vector type. |
The groupId depends on the driver version:
- Version 4.18 and later
-
<dependency> <groupId>org.apache.cassandra</groupId> <artifactId>java-driver-core</artifactId> <version>VERSION</version> </dependency> - Version 4.17 and earlier
-
<dependency> <groupId>com.datastax.oss</groupId> <artifactId>java-driver-core</artifactId> <version>VERSION</version> </dependency>
For Java driver 3.x series, see Unsupported drivers.
Connect the Java driver
-
In your Java project, navigate to
/src/main/java, and then create aConnectDatabase.javafile:cd JAVA_PROJECT_DIRECTORY/src/main/java touch ConnectDatabase.java -
Add the following code to the
ConnectDatabase.javafile.This code imports dependencies, initializes the Java driver, and implements the
ConnectDatabaseclass to connect to your Astra database. For more information, see Best practices: Session and cluster handling and Connection pools and initial contact points.This example includes imports that you might not need for your project. For example,
CqlVectoris only necessary for the vector data type.ConnectDatabase.javaimport 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 com.datastax.oss.driver.api.core.CqlSessionBuilder; import com.datastax.oss.driver.api.core.cql.PreparedStatement; import com.datastax.oss.driver.api.core.data.CqlVector; import com.datastax.oss.driver.api.core.type.codec.TypeCodecs; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; public class DriverExample { public static void main(String[] args) { // Initialize the Java driver CqlSessionBuilder builder = CqlSession.builder(); builder.withCloudSecureConnectBundle(Paths.get("PATH/TO/SCB.zip")); builder.withAuthCredentials("token", System.getenv("APPLICATION_TOKEN")); builder.withKeyspace(System.getenv("KEYSPACE_NAME")); try (CqlSession session = builder.build()) { //CQL queries and query execution logic... } System.exit(0); } }Replace
PATH/TO/SCB.zipwith the absolute path to your database’s Secure Connect Bundle (SCB) zip file (secure-connect-DATABASE_NAME.zip). -
To test the connection, add a simple query to the script.
The following example
SELECTstatement runs against thesystem.localtable. You can replace this statement with any CQL statement on any keyspace or table in your database. Edit the variable that stores the keyspace name, if necessary.try (CqlSession session = builder.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."); } } -
Save
ConnectDatabase.java, and then build your Maven project.If you ran the example
SELECTstatement on thesystem.localtable, then therelease_versionvalue from thesystem.localtable is printed to the console if the script runs successfully.
Next, you can extend or modify this script to run other commands against your database or connect to other databases. For more information, see the documentation for your version of the Java driver:
Reconnect the Java driver after a migration
If you migrate your data from one Cassandra database platform to another, you must update your client applications to connect to your new databases.
At minimum, you must update the driver connection strings.
Additional changes might be required if you upgraded to a new major driver version or migrated to a database platform with a different feature set.
For example, if you migrate to Astra, your drivers cannot create keyspaces because CQL for Astra doesn’t support CREATE KEYSPACE.
For information about updating driver connections after a migration, see the DataStax migration documentation on Connecting client applications to your new target database. Although the referenced documentation is in the context of zero downtime migration, the information applies to most Cassandra-to-Cassandra migrations where you need to update Cassandra driver connection strings.
The following steps summarize the process for updating your driver connection strings after you migrate to Astra:
-
In your pom.xml, update the dependency for the Apache Cassandra Java driver
.
The latest version is recommended, but you can use any Astra-compatible version.
If you are upgrading from version 4.18.0 or earlier, make sure that you update the
groupIdas well as theversion:<dependency> <groupId>org.apache.cassandra</groupId> <artifactId>java-driver-core</artifactId> <version>VERSION</version> </dependency> -
In your existing Java driver code, modify the connection code to use the SCB and
tokenauthentication:CqlSessionBuilder builder = CqlSession.builder(); builder.withCloudSecureConnectBundle(Paths.get("PATH/TO/SCB.zip")); builder.withAuthCredentials("token", System.getenv("APPLICATION_TOKEN"));For more information, see Connect the Java driver.
-
Build your project.