SQLDelight中如何指定查询的返回类型?
SQLDelight自定义查询返回类型解决方案
方法一:查询语句中直接指定返回类型
在SQLDelight的查询定义末尾,通过: 自定义类型名的语法指定返回类型,同时确保查询返回的字段与自定义类的构造参数名称、类型完全匹配:
-- 定义查询时指定返回ShortLocation getAllShort: SELECT id, name FROM LocationEntity : ShortLocation
如果查询字段名和自定义类属性名不一致,需要用AS别名对齐:
-- 假设表中字段是location_id,类中属性是id getAllShort: SELECT location_id AS id, name FROM LocationEntity : ShortLocation
方法二:自定义RowMapper实现映射
如果需要更灵活的字段映射逻辑,可以在Kotlin代码中自定义RowMapper,再通过map()方法转换查询结果:
- 定义RowMapper:
val shortLocationMapper = RowMapper { cursor -> ShortLocation( id = cursor.getLong("id"), name = cursor.getString("name") ) }
- 调用查询时应用映射:
val shortLocations: List<ShortLocation> = database.locationQueries.getAllShort().map(shortLocationMapper)
关于自动生成类型的疑问
不需要被迫接受每个查询生成的默认类型,通过上述两种方式,完全可以让查询返回你自定义的数据类,避免生成大量冗余的查询结果类型。
内容的提问来源于stack exchange,提问作者daneejela
相关产品推荐
相关产品推荐

