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.
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
-
Generate a Bearer Token and select Database Administrator 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
-
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 examplepom.xml
file. Replace{proto-version}
with the current gRPC proto versionand replace
{netty-version}
with the current gRPC netty version.
<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>
-
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));
-
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());
-
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.
-
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 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.
-
Open your Astra Portal and select your database.
-
On the Overview page, select Connect.
-
In the Database Essentials section, click Get Bundle.
-
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.
-
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 linkFor 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 |
---|---|
|
DataStax’s Certificate Authority public certificate |
|
A certificate, unique to the specific SCB |
|
A private key, unique to the specific SCB |
|
A PFX formatted archive containing the certificate and the private key |
|
A configuration file with information on how to securely connect to the Astra DB instance associated with the SCB |
|
A CQLSH profile containing CQL shell session settings |
|
A Java keystore file containing the aforementioned cert & key files |
|
A Java keystore file containing the aforementioned ca.crt |
Connecting the driver
-
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.
-
Add the DataStax Java driver dependency to your
pom.xml
file with the latest version.
<!--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>${latest4x}</version> </dependency>
-
Save and close your
pom.xml
file. -
Initialize the DataStax Java driver.
-
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
-
Copy the following code for your DataStax driver into the
ConnectDatabase.java
file. The following example implements aConnectDatabase
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); } }
-
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.
-
-
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 .
<?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>${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.
-
In your existing DSE Java driver code, update dependencies to include the DSE Java driver version that can connect to Astra DB databases.
Replace
{version}
with the current Java driver version.
- DataStax Java driver for Apache Cassandra 4.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>{version}</version> </dependency>
- DataStax Java driver for Apache Cassandra 3.x
-
<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>{version}</version> </dependency>
-
Optional: To use DSE QueryBuilder, which is a utility used to generate CQL queries programmatically, add the following dependency to your
pom.xml
file. Replace{version}
with the current Java driver version.
<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>{version}</version> </dependency>
-
Modify the connection code to use the Astra DB API. In the
CqlSession
orSession
objects (DseCluster
orDseSession
objects for DSE), include the path to the secure connect bundle for your Cassandra database (secure-connect-database_name.zip
) in thewithCloudSecureConnectBundle()
method, as shown in the following example.-
DataStax Java driver for Apache Cassandra 4.x
-
DataStax Java driver for Apache Cassandra 3.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"))
If converting from using the open source Cassandra Java driver to the DSE Java driver, ensure that you change
Session
toDseSession
. -
-
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.