Search code examples
javacassandradatastax-java-driver

What is the most efficient way to map/transform/cast a Cassandra BoundStatement's ResultSet to a Java classe built using the Object-mapping API?


Is there a builtin way in DataStax Java for Apache Cassandra to map the ResultSet coming from a BoundStatement to the domain objects Java classes built with using the Object-mapping API?

I am a newbie moving from the Mapper + Accessor approach to BoundStatement approach and would like to continue using the domain objects' Java classes built with the Object-mapping API so I do minimal changes to the implementation of my DAO methods while moving to the BoundStatement. I am looking to do it in a generic way and avoid to iterate over each ResultSet row and do a row.get one by one for each domain object.

While using the Mapper + Accessor approach, the Result.all() do that very well. Could not find anything similar to the BoundStatement approach.

Thanks

IPVP


Solution

  • You can accomplish mapping a ResultSet to a com.datastax.driver.mapping.Result by instantiating a Mapper for your object, and then using Mapper.map. Here is an example, taken from the java driver's tests that takes a ResultSet from a regularly executed query and maps it to a Result<Post>, and then iterates over the Result to access each mapped Post:

    MappingManager manager = new MappingManager(session);
    
    Mapper<Post> m = manager.mapper(Post.class);
    ...
    // Retrieve posts with a projection query that only retrieves some of the fields
    ResultSet rs = session.execute("select user_id, post_id, title from posts where user_id = " + u1.getUserId());
    
    Result<Post> result = m.map(rs);
    for (Post post : result) {
        assertThat(post.getUserId()).isEqualTo(u1.getUserId());
        assertThat(post.getPostId()).isNotNull();
        assertThat(post.getTitle()).isNotNull();
    
        assertThat(post.getDevice()).isNull();
        assertThat(post.getTags()).isNull();
    }