Android Room:查询中的每个绑定变量都必须具有匹配的方法

我用kotlin使用android持久库库房。

Dao看起来像这样

@Dao interface CountryDao { @Query("SELECT * FROM countries") fun loadAllCountried() : LiveData<List<CountryEntity>> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAll(products: List<CountryEntity>) @Query("SELECT * FROM countries WHERE id = :countryId") fun loadCountry(countryId: Int): LiveData<CountryEntity> @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<CountryEntity> @Query("SELECT * FROM countries WHERE id = :arg0") fun loadCountrySync(countryId: Int): CountryEntity 

似乎固定在kotlin-gradle-plugin中:1.1.3

现在可以使用1.1.3-eap-85和kotlin-kapt来修复这个问题。 官方鸣叫

正如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' } } }