Android Room:查询中的每个绑定variables都必须具有匹配的方法
我用kotlin使用android持久库库房。
Dao看起来像这样
@Dao interface CountryDao { @Query("SELECT * FROM countries") fun loadAllCountried() : LiveData<List> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAll(products: List) @Query("SELECT * FROM countries WHERE id = :countryId") fun loadCountry(countryId: Int): LiveData @Query("SELECT * FROM countries WHERE id = :countryId") fun loadCountrySync(countryId: Int): CountryEntity }
这似乎对我很好,但我得到这个错误
Error: Each bind variable in the query must have a matching method parameter. Cannot find method parameters for :countryId.
我可以看到参数被命名为countryId
,那么可能是什么问题?
FYI:这是CountryDao_Impl.java中的生成代码
@Override public CountryEntity loadCountrySync(int arg0) { final String _sql = "SELECT * FROM countries WHERE id = ?"; final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1); int _argIndex = 1; final Cursor _cursor = __db.query(_statement); try { final int _cursorIndexOfId = _cursor.getColumnIndexOrThrow("id"); final int _cursorIndexOfPopulation = _cursor.getColumnIndexOrThrow("population"); final CountryEntity _result; if(_cursor.moveToFirst()) { _result = new CountryEntity(); final int _tmpId; _tmpId = _cursor.getInt(_cursorIndexOfId); _result.setId(_tmpId); final long _tmpPopulation; _tmpPopulation = _cursor.getLong(_cursorIndexOfPopulation); _result.setPopulation(_tmpPopulation); } else { _result = null; } return _result; } finally { _cursor.close(); _statement.release(); } }
在这个方法中,我看到在方法的任何地方都没有使用arg0。
编辑:这似乎是固定在新的插件。 几个答案是正确的,所以不能接受每一个答案,对不起。
Kotlin没有妥善保存参数的名字 – 这是https://youtrack.jetbrains.com/issue/KT-17959
你可以在你的@Query语句中使用:arg0
, :arg1
等作为参数名来解决这个问题:
@Query("SELECT * FROM countries WHERE id = :arg0") fun loadCountry(countryId: Int): LiveData @Query("SELECT * FROM countries WHERE id = :arg0") fun loadCountrySync(countryId: Int): CountryEntity
在我的项目中使用kotlin v.1.2.10只能通过下一步的方式工作:
@Query("select * from user where pk = :userId") fun findUserById(userId: Long): DBUser
查询中的名称“ userId ”和方法中的“ userId ”应该相同。
现在可以使用1.1.3-eap-85和kotlin-kapt来修复这个问题。 官方鸣叫
你的模块的build.gradle是什么样的? 如果您没有apply plugin: 'kotlin-kapt'
定义,则会发生此错误。 如果启用了kapt插件,则编译器将按照预期将绑定参数与方法参数进行匹配。
似乎固定在kotlin-gradle-plugin中:1.1.3
正如Anton Kazakov所说,这个bug在kotlin插件1.1.3-eap-85
是固定的
但由于它尚未公开,您需要从privet存储库下载,而不是jcenter
所以你需要在你的build.gradle中加入这一行
maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' }
例
buildscript { ext { kotlin_version = '1.1.3-eap-85' } repositories { google() jcenter() maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' } } dependencies { classpath 'com.android.tools.build:gradle:3.0.0-alpha7' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() mavenCentral() maven { url 'https://dl.bintray.com/kotlin/kotlin-dev' } } }