【发布时间】:2018-12-14 09:35:19
【问题描述】:
在下面的 Cassandra 代码中,我正在查询一个数据库并期望多个值。该函数需要和 id 并且应该返回 Option[List[M]] 其中M 是我的模型。我有一个函数rowToModel(row: Row): MyModel,它可以从ResultSet 获取row 并将其转换为我的模型实例。
我的问题是我返回的List 总是空的,即使ResultSet 有数据。我通过在rowToModel 中添加调试打印来检查它
def getRowsByPartitionKeyId(id:I):Option[List[M]] = {
val whereClause = whereConditions(tablename, id);
val resultSet = session.execute(whereClause) //resultSet is an iterator
val it = resultSet.iterator();
val resultList:List[M] = List();
if(it.hasNext){
while(it.hasNext) {
val item:M = rowToModel(it.next())
resultList.:+(item)
}
Some(resultList) //THIS IS ALWAYS List()
}
else
None
}
我怀疑resultList 是val,它的值在while 循环中没有改变。我可能应该使用yield 或其他东西,但我不知道是什么以及如何使用。
【问题讨论】: