我是Apache Cassandra的新手。
我想知道如何将Resultset对象强制转换为用户定义的列表类型或java中的用户定义对象。
我尝试过很多东西,但仍然卡住了。
**这是我迄今为止尝试过的方法的代码:
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;
}
答案 0 :(得分:1)
让我们假设你有桌子:
CREATE TABLE xchangeoutboundmessage (
id timeuuid PRIMARY KEY,
message text,
sender bigint
);
和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 + '}';
}
}
您可以手动从行获取日期并将值设置为dto,也可以使用cassandra-driver-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);
}
使用cassandra驱动程序映射:
首先将@Table(name = "XchangeOutboundMessage")
注释添加到XchangeOutboundMessage DTO
MappingManager manager = new MappingManager(session);
Mapper<XchangeOutboundMessage> mapper = manager.mapper(XchangeOutboundMessage.class);
list = mapper.map(result).all();
注意:cassandra-driver-mapping需要添加为依赖
顺便说一下,这些类型的查询在cassandra中非常低效,总是尝试在where子句中提供分区键。