Skip to content

Support for getting Scalar Values using Native Queries over Cassandra

karthikprasad13 edited this page May 13, 2015 · 5 revisions

What are Scalar Values?

A scalar value is one unit of data. This unit of data can be either a number or a chunk of text.

In relational database, a scalar value can also refer to a column.

Why support them?

In an object mapper, column values are always wrapped in an entity which makes it difficult for retrieving values that does not have a mapping object defined (e.g. COUNT, metadata queries, etc).

This issue can be addressed by enabling scalar queries for which no entity definition is required. Keeping this in mind, retrieving scalar values via native queries over Cassandra has been facilitated from Kundera-2.17 onwards.

Example:

  • Define Persistence unit with Cassandra specific details:
	<persistence-unit name="CassandraScalarQueriesTest">
		<provider>com.impetus.kundera.KunderaPersistence</provider>
		<!-- test without entity definition -->
		<exclude-unlisted-classes>true</exclude-unlisted-classes>
		<properties>
			<property name="kundera.nodes" value="localhost" />
			<property name="kundera.port" value="9160" />
			<property name="kundera.keyspace" value="KunderaExamples" />
			<property name="kundera.dialect" value="cassandra" />
			<property name="kundera.client.lookup.class"
				value="com.impetus.client.cassandra.thrift.ThriftClientFactory" />
		</properties>
	</persistence-unit>
  • Create EntityManagerFactory and EntityManager
      EntityManagerFactory emf = Persistence.createEntityManagerFactory("CassandraScalarQueriesTest");
      EntityManager entityManager = emf.createEntityManager();
  • Use createNativeQuery and get the results
      String selectQuery = "SELECT key, state FROM users";
      Query q = entityManager.createNativeQuery(selectQuery);
      List results = q.getResultList();

      Sample Output:
      results = [{state=UT, key=lorem}, {state=CN, key=ipsum}, {state=IO, key=conneture}]

results is an ArrayList of records from the database. Each record is a Map<String, Object> where key contains name of the column and value contains corresponding value of the column.

  • Sample metadata queries:
  String useNativeSql = "SELECT * FROM system.schema_keyspaces WHERE keyspace_name = 'KunderaExamples'";
  Query q = entityManager.createNativeQuery(useNativeSql);
  results = q.getResultList();

Refer to test case CassandraScalarQueriesTest for more on this.

Clone this wiki locally