Screen-2BShot-2B2015-06-06-2Bat-2B10.11.32-2BPM

CRUD Operation in Cassandra with Maven in Eclipse IDE using Datastax Java Driver 2.1.6

1) Create a Maven project in Eclipse IDE.
2) Click on Next button
3) Select Maven Archetype. For this one I have chosen maven-archetype-quickstart and click on Next button.
4) Provide GroupID and ArtifactID and click on Finish button.
5) Add Datastax Cassandr Driver dependency in pom.xml file. It will add the JAR file to the build path.

<dependency>

<groupId>com.datastax.cassandra</groupId>

<artifactId>cassandra-driver-core</artifactId>

<version>2.1.6</version>

</dependency>

7) Get the Cluster object instance
Cluster cluster = Cluster.builder().addContactPoint("localhost").withPort(9042).build();
8) Get the Session object instance
Session session = cluster.connect();
9) For inserting the record use:
session.execute("insert into users(user_id, user_email, user_name, user_pwd) values (2, '33@gmail.com', 'FondOfIt1', 'fondpwd');");
ResultSet resultSet = session.execute("select * from users");
List<Row> results = resultSet.all();
for (Row row : results) {
System.out.println("user id--"+row.getInt(0));
System.out.println("user_name---"+row.getString(2));
}
Output:
user id--1
user_name---FondOfIt
user id--2
user_name---FondOfIt1
10) For updating the record use:
session.execute("update users set user_email='44@gmail.com' where user_id=2;");
ResultSet updateResultSet = session.execute("select * from users");
List<Row> updatedResults = updateResultSet.all();
for (Row row : updatedResults) {
System.out.println("user id--"+row.getInt(0));
System.out.println("user_eamil---"+row.getString(1));
}
Output:
user id--1
user_eamil---33@gmail.com
user id--2
user_eamil---44@gmail.com
11) For deleting records use:
session.execute("delete from users where user_id=2");
ResultSet deletedResultSet = session.execute("select * from users");
List<Row> deletedResults = deletedResultSet.all();
for (Row row : deletedResults) {
System.out.println("user id--"+row.getInt(0));
System.out.println("user_eamil---"+row.getString(1));
}
Output:
user id--1
user_eamil---33@gmail.com

Leave a Reply

Your email address will not be published. Required fields are marked *