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?

青春壹個敷衍的年華 提交于 2019-12-07 07:37:53

问题


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


回答1:


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();
}


来源:https://stackoverflow.com/questions/34701817/what-is-the-most-efficient-way-to-map-transform-cast-a-cassandra-boundstatement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!