I am trying to access Cassandra @ localhost using a standalone main() method. The main() method uses DataStax driver and CassandraOperations class from spring-data-cassandra module. CassandraOperation
's queryForObject()
method always return the primary key instead of Entity Object.
I am just using the code example given in the Spring Data Documentation.
Apache-Cassandra version : 2.1.2
Spring-Data-Cassandra version : 1.2.0.RELEASE
Entity Class :
import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;
@Table
public class Person {
@PrimaryKey
private String id;
private String name;
private int age;
public Person(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
Client Code:
public class CassandraApp {
private static final Logger LOG = LoggerFactory.getLogger(CassandraApp.class);
private static Cluster cluster;
private static Session session;
public static void main(String[] args) {
try {
cluster = Cluster.builder().addContactPoints(InetAddress.getLocalHost()).build();
session = cluster.connect("person");
CassandraOperations cassandraOps = new CassandraTemplate(session);
cassandraOps.insert(new Person("1234567890", "David", 40));
Select s = QueryBuilder.select().from("person");
s.where(QueryBuilder.eq("id", "1234567890"));
System.out.println(cassandraOps.queryForObject(s, Person.class).getId());
cassandraOps.truncate("person");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
Runtime exception:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to com.prashanth.ts.entity.Person at com.prashanth.ts.client.CassandraApp.main(CassandraApp.java:40) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
I am new to Spring Data. Any one can help me identify what I am doing wrong here.
I also tried removing the QueryBuilder and passing a simple query String like "select * from person" to the queryForObject() methodd
Note : The insert operation is working perfectly.