是否可以在Android的ORMLite查询中使用别名(AS)?我试图使用以下代码:
String query =
"SELECT *, (duration - elapsed) AS remaining FROM KitchenTimer ORDER BY remaining";
GenericRawResults<KitchenTimer> rawResults =
getHelper().getKitchenTimerDao().queryRaw(
query, getHelper().getKitchenTimerDao().getRawRowMapper());
但是当执行此代码时,会出现以下错误:
java.lang.IllegalArgumentException: Unknown column name 'remaining' in table kitchentimer
答案 0 :(得分:3)
java.lang.IllegalArgumentException:表kitchentemer中的未知列名'剩余'
与您的KitchenTimerDao
相关联的原始行映射器希望结果直接与KitchenTimer
实体列对应。但是,由于您要添加remaining
列,因此不会将结果列放在何处,因此也是例外。这是一个原始查询,因此您需要提供自己的结果映射器 - 您不能使用DAO。请参阅docs on raw queries。
例如,如果您想将结果映射到您自己的对象Foo
,那么您可以执行以下操作:
String query =
"SELECT *, (duration - elapsed) AS remaining FROM KitchenTimer ORDER BY remaining";
GenericRawResults<Foo> rawResults =
orderDao.queryRaw(query, new RawRowMapper<Foo>() {
public Foo mapRow(String[] columnNames, String[] resultColumns) {
// assuming 0th field is the * and 1st field is remaining
return new Foo(resultColumns[0], Integer.parseInt(resultColumns[1]));
}
});
// page through the results
for (Foo foo : rawResults) {
System.out.println("Name " + foo.name + " has " + foo.remaining + " remaining seconds");
}
rawResults.close();
答案 1 :(得分:0)
我有同样的问题。我想获取对象列表,但要添加一个带有别名的新属性。
要继续使用OrmLite中的对象映射器,我使用了RawRowMapper来接收列和结果。但是,我不是手动转换所有列,而是先读取别名并在列数组中删除其引用。然后可以使用OrmLite Dao映射器。
我用Kotlin代码编写
val rawResults = dao.queryRaw<Foo>(sql, RawRowMapper { columnNames, resultColumns ->
// convert array to list
val listNames = columnNames.toMutableList()
val listResults = resultColumns.toMutableList()
// get the index of the column not included in dao
val index = listNames.indexOf(ALIAS)
if (index == -1) {
// There is an error in the request because Alias was not received
return@RawRowMapper Foo()
}
// save the result
val aliasValue = listResults[index]
// remove the name and column
listNames.removeAt(index)
listResults.removeAt(index)
// map row
val foo = dao.rawRowMapper.mapRow(
listNames.toTypedArray(),
listResults.toTypedArray()
) as Foo
// add alias value. In my case I save it in the same object
// but another way is to create outside of mapping a list and
// add this value in the list if you don't want value and object together
foo.aliasValue = aliasValue
// return the generated object
return@RawRowMapper foo
})
这不是最短的解决方案,但对我而言,保持使用相同的映射器非常重要。当将属性添加到表中并且您不记得要更新映射时,它可以避免错误。