Skip to main content

Run Cassandra with Spring Data

Posted by otaviojava on August 25, 2013 at 6:05 AM PDT
Spring Data no Cassandra com Easy-Cassandra

Spring is an open source framework whose goals is facilitate the Java developer's life, it began with dependency injection and nowadays works on many plug-ins. Plug-ins such Spring Social, to connects social media like twitter and facebbok, Spring security beyond control inversion. The goal of this post is talk about Spring Data working with Cassandra.

Spring Data does part of Spring plug-in, it has as objective do a high level among a data base and Java application. This way, you can use POJO for persist in many kind of data bases.

  • RMDB with JPA and JDBC
  • BigData with Apache Hadoop
  • Data-Grid with GermFire
  • HTTP with Rest
  • NOSQL with MongoDB, Neo4J, Redis and Hbase

The main advantage of Spring data does part of Spring, it may run without Java EE server, it can run a simple container such tomcat or outside of a server. Its dependency injection works together of XML file, but, unlike some developers think, you may use annotations to help, however, you should know when use xml or annotation.

So Spring Data with Cassandra has as objective do a high level layer to NOSQL Cassandra, with POJO structured can do CRUD operations. The Spring Data Cassandra has not launched, but Easy-cassandra has integration with Spring, now you can use Cassandra with most popular frameworks around world.

The application will really simple, it does put information and retrieve by id. Firstly, make the Person entity, our POJO.

@Entity(name = "person") 
public class Person implements Serializable {

    private UUID id;
    @Column(name = "name")
    private String name;
    @Column(name = "born")
    private Integer year;
//getter and setter


POJO entity Peron

How you can see, the entity had mapped by JPA 20, secondly is configuration with XML file, within has information of Cassandra Base (base, port, default keySpace) is our connections factory Cassandra inside Spring, also was included the mapped class.

<beans xmlns=""

          <context:component-scan" title="">
base-package="org.javabahia.cassandra.spring" />
<bean id = "clusterInformation" class="org.easycassandra.persistence.cassandra.ClusterInformation">
<property name="keySpace" value="consegi" />
<property name="hosts">
<bean id="cassandraFactory" class="org.easycassandra.persistence.cassandra.spring.CassandraFactoryAnnotation"
<constructor-arg name="clusterInformation" value="clusterInformation" />
<property name="annotatedClasses">

Spring Data configuration, that informs configurations of Cassandra (name of host, number of port, default keyspace and mapped class) beyond Cassandra's Template.

With Cassandra connections factory may return a session, the bridge among Cassandra and Easy-cassandra, also will create CassandraTemplase, it an api to do simple operations on Cassandra..

public interface CassandraTemplate{ 

    <T> T save(T entity);
    <T> Iterable<T> save(Iterable<T> entities);
    <T> void delete(T entity);
    <T> void delete(Iterable<T> entities);
    <K> void delete(K key, Class<?> entity);
    <K,T> void delete(Iterable<K>  keys, Class<T> entity);

    <T> void deleteAll(Class<T> entity);
    <T> T update(T entity);
    <T> Iterable<T> update(Iterable<T> entities);
    <T,K> T findOne(K key, Class<T> entity);
    <T,K> List<T> findAll(Iterable<K> keys, Class<T> entity);
    <T> List<T> findAll(Class<T> entity);
    <T,I> List<T> findByIndex(String columnName,I index,Class<T> entity);
    <K,T>boolean exist(K key, Class<T> entity);

    void executeUpdate(String query);

CassandraTemplase's operations

Also there is CassandraReposiroty, this abstract class implements CrudRepository of SpringData, to use it is necessary implement the method which returns CassandraTemplate.

public class PersonRepository extends CassandraRepository<Person, UUID>{

private CassandraTemplate cassandraTemplate;

protected CassandraTemplate getCassandraTemplate() {
return cassandraTemplate;


PersonRepository with CassandraRepository

Whereby CassandraRepository implements the base of persistence on Spring Data, consequently, is available use this operations on Cassandra.

public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> { 
<S extends T> S save(S entity);

<S extends T> Iterable<S> save(Iterable<S> entities);

T findOne(ID id);

boolean exists(ID id);

Iterable<T> findAll();

Iterable<T> findAll(Iterable<ID> ids);

long count();

void delete(ID id);

void delete(T entity);
void delete(Iterable<? extends T> entities);

void deleteAll();

CrudRepository's Interface of Spring Data

Finally run this project.

public class App 
    public static void main( String[] args )
ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
    PersonRepository personService=ctx.getBean(PersonRepository.class);
    UUID uuid=UUID.randomUUID();
    Person person=new Person();
    person.setName("Otávio Santana");
    Person otavio=personService.findOne(uuid);

Run a simple project, save and retrieve the object.

Concluding, was demonstrated concern about Spring Data how it works with Cassandra using Easy-Cassandra. Spring Data, absolutely, is a big tool to development with many data bases, thereby you can use types of databases with less effort, perhaps with just CRUDRepository interface. despite that a Java developer must know the impacts when change to another information center, that includes modeling.


Spring Data:


What is the default port number to connect ...

What is the default port number to connect cassandraDB?

Caused by: com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: localhost/ (com.datastax.driver.core.ConnectionException: [localhost/] Unexpected error during transport initialization (com.datastax.driver.core.TransportException: [localhost/] Channel has been closed)))
bean id="cassandraFactory" class="org.easycassandra.persistence.cassandra.spring.CassandraFactoryAnnotation">
constructor-arg name="host" value="localhost" />
constructor-arg name="port" value="7000" />

the default port in Cassandra is: 9042

the default port in Cassandra is: 9042

Person Entity class with collection datatype package ...

Person Entity class with collection datatype

package org.javabahia.cassandra.spring.entity;

import java.util.Map;
import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.Id;

import org.easycassandra.Index;

* @author otavio
@Entity(name = "person")
public class Person implements Serializable {

private static final long serialVersionUID = 3L;

private UUID id;

@Column(name = "name")
private String name;

@Column(name = "born")
private Integer year;

* @return the propertyKeys

public Map getPropertyKeys() {
return propertyKeys;

* @param propertyKeys the propertyKeys to set
public void setPropertyKeys(Map propertyKeys) {
this.propertyKeys = propertyKeys;

private Map propertyKeys;

public UUID getId() {
return id;

public void setId(UUID id) { = id;

public Integer getYear() {
return year;

public void setYear(Integer year) {
this.year = year;

public String getName() {
return name;

public void setName(String name) { = name;

public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;

public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id == null) {
if ( != null)
return false;
} else if (!id.equals(
return false;
return true;


Thank for your question on next version will have ...

Thank for your question on next version will have @ElementCollection as annotation but it does not implemented yet.

When you will use some collection you should ...

When you will use some collection you should use:

  • @MapData to java.util.Map
  • @ListData to java.util.List
  • @SetData to java.util.Set

You can get more information about collections here:

More about the project and wike here:

Thanks for your reply.

Thanks for your reply.

this improvement had done on version 2.0.0-RC9. Now you can ...

this improvement had done on version 2.0.0-RC9.
Now you can use @ElementCollection to java.util.List, java.util.Set and java.util.Map.

Thank you very much . Can u please give me a sample for ...

Thank you very much .

Can u please give me a sample for executing query with cassandra as below mongo with spring.

Query query = new Query();
List receipt=mongoOps.find(query, Receipt.class, getMyCollection(Receipt.class));
return receipt;

Now you can use the SelectBuilder, it is a simple way to use ...

Now you can use the SelectBuilder, it is a simple way to use query with Easy-Cassandra.

This version will be realese on 2.1.0 version.

Comming soon, to know more about Builders.

on Cassandra queries are very poorer than Mongodb, so you ...

on Cassandra queries are very poorer than Mongodb, so you can find by key or index with consistency level and you have methods:

Ok fine , then How i can find a row by following date range ...

Ok fine , then How i can find a row by following date range as

you can inject the factory and use the getSession()'s method ...

you can inject the factory and use the getSession()'s method with this session you can execute native methods to Cassandra, for this use the execute method.
More information here:

But comming soon will have range on the query.

when i use an collection datatype as a field it show the ...

when i use an collection datatype as a field it show the following error

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cassandraFactory' defined in ServletContext resource [/WEB-INF/classes/spring-security.xml]: Invocation of init method failed; nested exception is com.datastax.driver.core.exceptions.SyntaxError: line 1:37 mismatched input ';' expecting '<'
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(
at org.springframework.web.context.ContextLoader.initWebApplicationContext(
at org.springframework.web.context.ContextLoaderListener.contextInitialized(
at org.apache.catalina.core.StandardContext.listenerStart(
at org.apache.catalina.core.StandardContext.start(
at org.apache.catalina.core.ContainerBase.addChildInternal(
at org.apache.catalina.core.ContainerBase.addChild(
at org.apache.catalina.core.StandardHost.addChild(
at org.apache.catalina.startup.HostConfig.deployDescriptor(
at org.apache.catalina.startup.HostConfig.deployDescriptors(
at org.apache.catalina.startup.HostConfig.deployApps(
at org.apache.catalina.startup.HostConfig.start(
at org.apache.catalina.startup.HostConfig.lifecycleEvent(
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(
at org.apache.catalina.core.ContainerBase.start(
at org.apache.catalina.core.StandardHost.start(
at org.apache.catalina.core.ContainerBase.start(
at org.apache.catalina.core.StandardEngine.start(
at org.apache.catalina.core.StandardService.start(
at org.apache.catalina.core.StandardServer.start(
at org.apache.catalina.startup.Catalina.start(
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(
at sun.reflect.DelegatingMethodAccessorImpl.invoke(
at java.lang.reflect.Method.invoke(
at org.apache.catalina.startup.Bootstrap.start(
at org.apache.catalina.startup.Bootstrap.main(
Caused by: com.datastax.driver.core.exceptions.SyntaxError: line 1:37 mismatched input ';' expecting '<'
at com.datastax.driver.core.exceptions.SyntaxError.copy(
at com.datastax.driver.core.ResultSetFuture.extractCauseFromExecutionException(
at com.datastax.driver.core.ResultSetFuture.getUninterruptibly(
at com.datastax.driver.core.Session.execute(
at com.datastax.driver.core.Session.execute(
at org.easycassandra.persistence.cassandra.FixColumnFamily.executeAlterTableAdd(
at org.easycassandra.persistence.cassandra.FixColumnFamily.verifyRow(
at org.easycassandra.persistence.cassandra.FixColumnFamily.verifyRowType(
at org.easycassandra.persistence.cassandra.FixColumnFamily.verifyColumnFamily(
at org.easycassandra.persistence.cassandra.AbstractCassandraFactory.fixColumnFamily(
at org.easycassandra.persistence.cassandra.spring.CassandraFactoryAnnotation.mappedBean(
at org.easycassandra.persistence.cassandra.spring.CassandraFactoryAnnotation.afterPropertiesSet(
... 36 more


Please revert me with sample using the collection datatype or give me a solution for this error.