简体   繁体   中英

how can i cast Resultset object of cassandra in user defined java class object or in ArrayLIst

I am new to Apache Cassandra .

I want to know How to cast a Resultset object to either a user defined list type or a user defined object in java.

I have tried many things but still stuck.

**This is the code" of the method I've tried so far:

public List getOutBoundMessageListFromCassandra(){
   List<XchangeOutboundMessage> list=new ArrayList();
   try {

       cluster = Cluster.builder().addContactPoint(contactPoints).build();

       session = cluster.connect(keySpaceName);

       cassandraOps = new CassandraTemplate(session);

       Select s = QueryBuilder.select().from("XchangeOutboundMessage");
       ResultSet result = session.execute(s);
       list=result.all();
   } catch (Exception e) {
       e.printStackTrace();
   }
   return list;

}

Let's Assume you have the table :

CREATE TABLE xchangeoutboundmessage (
    id timeuuid PRIMARY KEY,
    message text,
    sender bigint
);

And the Associated DTO

public class XchangeOutboundMessage {

    private UUID id;
    private String message;
    private long sender;

    public UUID getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }

    public long getSender() {
        return sender;
    }

    public void setId(UUID id) {
        this.id = id;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setSender(long sender) {
        this.sender = sender;
    }

    @Override
    public String toString() {
        return "XchangeOutboundMessage{" + "id=" + id + ", message=" + message + ", sender=" + sender + '}';
    }

}

You can Either Manually get date from row and set value to dto or you can use cassandra-driver-mapping to do this for you.

Using Manual mapping :

for (Row row : result) {
    XchangeOutboundMessage message = new XchangeOutboundMessage();
    message.setId(row.getUUID("id"));
    message.setMessage(row.getString("message"));
    message.setSender(row.getLong("sender"));
    list.add(message);
}

Using cassandra driver mapping :

First Add @Table(name = "XchangeOutboundMessage") Annotation to XchangeOutboundMessage DTO

MappingManager manager = new MappingManager(session);
Mapper<XchangeOutboundMessage> mapper =  manager.mapper(XchangeOutboundMessage.class);
list = mapper.map(result).all();

Note : cassandra-driver-mapping need to add as dependency

By the way these type of query is very inefficient in cassandra, always try to provide partition key in where clause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM