Комната

Библиотека сохранения данных Room обеспечивает уровень абстракции поверх SQLite, что позволяет обеспечить более надежный доступ к базе данных и при этом использовать все возможности SQLite.
Последнее обновление Стабильный релиз Кандидат на релиз Бета-версия Альфа-релиз
8 октября 2025 г. 2.8.2 - - -

Объявление зависимостей

Чтобы добавить зависимость от Room, необходимо добавить репозиторий Google Maven в свой проект. Подробнее см. в репозитории Google Maven .

Зависимости для Room включают в себя тестирование миграций Room и Room RxJava.

Добавьте зависимости для необходимых артефактов в файл build.gradle вашего приложения или модуля:

Котлин

dependencies {
    val room_version = "2.8.2"

    implementation("androidx.room:room-runtime:$room_version")

    // If this project uses any Kotlin source, use Kotlin Symbol Processing (KSP)
    // See Add the KSP plugin to your project
    ksp("androidx.room:room-compiler:$room_version")

    // If this project only uses Java source, use the Java annotationProcessor
    // No additional plugins are necessary
    annotationProcessor("androidx.room:room-compiler:$room_version")

    // optional - Kotlin Extensions and Coroutines support for Room
    implementation("androidx.room:room-ktx:$room_version")

    // optional - RxJava2 support for Room
    implementation("androidx.room:room-rxjava2:$room_version")

    // optional - RxJava3 support for Room
    implementation("androidx.room:room-rxjava3:$room_version")

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation("androidx.room:room-guava:$room_version")

    // optional - Test helpers
    testImplementation("androidx.room:room-testing:$room_version")

    // optional - Paging 3 Integration
    implementation("androidx.room:room-paging:$room_version")
}

Круто

dependencies {
    def room_version = "2.8.2"

    implementation "androidx.room:room-runtime:$room_version"

    // If this project uses any Kotlin source, use Kotlin Symbol Processing (KSP)
    // See KSP Quickstart to add KSP to your build
    ksp "androidx.room:room-compiler:$room_version"

    // If this project only uses Java source, use the Java annotationProcessor
    // No additional plugins are necessary
    annotationProcessor "androidx.room:room-compiler:$room_version"

    // optional - RxJava2 support for Room
    implementation "androidx.room:room-rxjava2:$room_version"

    // optional - RxJava3 support for Room
    implementation "androidx.room:room-rxjava3:$room_version"

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation "androidx.room:room-guava:$room_version"

    // optional - Test helpers
    testImplementation "androidx.room:room-testing:$room_version"

    // optional - Paging 3 Integration
    implementation "androidx.room:room-paging:$room_version"
}

Информацию об использовании плагина KAPT см. в документации KAPT .

Информацию об использовании плагина KSP см. в краткой документации по KSP .

Информацию об использовании расширений Kotlin см. в документации ktx .

Дополнительную информацию о зависимостях см. в разделе Добавление зависимостей сборки .

При желании для библиотек, не относящихся к Android (например, модулей Gradle только для Java или Kotlin), вы можете использовать androidx.room:room-common для использования аннотаций Room.

Настройка параметров компилятора

Room имеет следующие параметры процессора аннотаций.

room.schemaLocation directory
Позволяет экспортировать схемы базы данных в JSON-файлы в указанном каталоге. Подробнее см. в разделе «Миграция комнат» .
room.incremental boolean
Включает процессор инкрементальных аннотаций Gradle. Значение по умолчанию — true .
room.generateKotlin boolean
Генерирует исходные файлы Kotlin вместо Java. Требуется KSP. Значение по умолчанию — true , начиная с версии 2.7.0 . Подробнее см. в примечаниях к версии 2.6.0 , когда эта функция была введена.

Используйте плагин Room Gradle

Начиная с версии Room 2.6.0 и выше, вы можете использовать плагин Room Gradle для настройки параметров компилятора Room. Плагин настраивает проект таким образом, чтобы сгенерированные схемы (которые являются результатом задач компиляции и используются для автоматической миграции) были правильно настроены для создания воспроизводимых и кэшируемых сборок.

Чтобы добавить плагин, в файле сборки Gradle верхнего уровня определите плагин и его версию.

Круто

plugins {
    id 'androidx.room' version "$room_version" apply false
}

Котлин

plugins {
    id("androidx.room") version "$room_version" apply false
}

В файле сборки Gradle на уровне модуля примените плагин и используйте расширение room .

Круто

plugins {
    id 'androidx.room'
}

android {
    ...
    room {
        schemaDirectory "$projectDir/schemas"
    }
}

Котлин

plugins {
    id("androidx.room")
}

android {
    ...
    room {
        schemaDirectory("$projectDir/schemas")
    }
}

При использовании плагина Room Gradle требуется указать schemaDirectory . Это позволит настроить компилятор Room, различные задачи компиляции и их бэкенды (javac, KAPT, KSP) для вывода файлов схем в папки с разметкой, например schemas/flavorOneDebug/com.package.MyDatabase/1.json . Эти файлы необходимо добавить в репозиторий для использования при валидации и автоматической миграции.

Некоторые параметры не могут быть настроены во всех версиях плагина Room Gradle, несмотря на то, что они поддерживаются компилятором Room. В таблице ниже перечислены все параметры и указана версия плагина Room Gradle, в которой добавлена ​​поддержка настройки этого параметра с помощью расширения room . Если ваша версия ниже или параметр ещё не поддерживается, вы можете использовать параметры процессора аннотаций .

Вариант Начиная с версии
room.schemaLocation (обязательно) 2.6.0
room.incremental -
room.generateKotlin -

Использовать параметры процессора аннотаций

Если вы не используете плагин Room Gradle или нужная вам опция не поддерживается вашей версией плагина, вы можете настроить Room с помощью параметров обработчика аннотаций, как описано в разделе Добавление зависимостей сборки . Способ указания параметров аннотаций зависит от того, используете ли вы KSP или KAPT для Room.

Круто

// For KSP
ksp {
    arg("option_name", "option_value")
    // other otions...
}

// For javac and KAPT
android {
    ...
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += [
                    "option_name":"option_value",
                    // other options...
                    ]
            }
        }
    }
}

Котлин

// For KSP
ksp {
    arg("option_name", "option_value")
    // other options...
}

// For javac and KAPT
android {
    ...
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += mapOf(
                    "option_name" to "option_value",
                    // other options...
                )
            }
        }
    }
}

Поскольку room.schemaLocation — это каталог, а не примитивный тип, при добавлении этого параметра необходимо использовать CommandLineArgumentsProvider , чтобы Gradle знал об этом каталоге при проведении проверок актуальности. В разделе «Миграция базы данных Room» представлена ​​полная реализация CommandLineArgumentsProvider , которая указывает местоположение схемы.

Обратная связь

Ваши отзывы помогают улучшить Jetpack. Сообщите нам, если вы обнаружите новые проблемы или у вас есть идеи по улучшению этой библиотеки. Пожалуйста, ознакомьтесь с уже существующими проблемами в этой библиотеке, прежде чем создавать новую. Вы можете проголосовать за существующую проблему, нажав на кнопку со звёздочкой.

Создать новый выпуск

Более подробную информацию см. в документации по системе отслеживания проблем .

Версия 2.8

Версия 2.8.2

8 октября 2025 г.

Выпущен androidx.room:room-*:2.8.2 . Версия 2.8.2 содержит следующие коммиты .

Исправления ошибок

  • Исправлена ​​взаимоблокировка, которая могла возникнуть при повторном открытии автоматически закрытой базы данных из потока ( b/446643789 ).

Версия 2.8.1

24 сентября 2025 г.

Выпущен androidx.room:room-*:2.8.1 . Версия 2.8.1 содержит следующие коммиты .

Исправления ошибок

  • Исправлен сбой процессора, который мог произойти при обработке функции DAO с лямбда-функцией приостановки. ( b/442220723 ).
  • Исправлена ​​ошибка, из-за которой Flows не получал последние обновления.

Версия 2.8.0

10 сентября 2025 г.

Выпущен androidx.room:room-*:2.8.0 . Версия 2.8.0 содержит следующие коммиты .

Важные изменения по сравнению с версией 2.7.0:

  • Добавлен новый артефакт androidx.room:room-sqlite-wrapper , содержащий API для получения обёртки SupportSQLiteDatabase из RoomDatabase с настроенным SQLiteDriver . Для получения обёртки используйте новую функцию расширения RoomDatabase.getSupportWrapper() . Это артефакт совместимости, позволяющий поддерживать использование SupportSQLiteDatabase , обычно получаемого из roomDatabase.openHelper.writableDatabase , даже если база данных Room настроена с SQLiteDriver . Эта обёртка полезна для инкрементальной миграции кодовых баз, которые хотят внедрить API SQLiteDriver, но при этом активно используют API SupportSQLite, но хотят использовать BundledSQLiteDriver . Подробнее см. в руководстве по миграции .
  • Добавлена ​​поддержка KMP для Watch OS и Tv OS.
  • Обновлена ​​библиотека Android minSDK с API 21 до API 23.

Версия 2.8.0-rc02

27 августа 2025 г.

Выпущен androidx.room:room-*:2.8.0-rc02 . Версия 2.8.0-rc02 содержит следующие коммиты .

Изменения API

  • Обновление minSDK с API 21 до API 23 ( Ibdfca , b/380448311 , b/435705964 , b/435705223 )
  • Обновите минимальную версию Android Gradle Plugin (AGP), совместимую с Room Gradle Plugin, с 8.1 до 8.4. ( Ia0d28 )

Исправления ошибок

  • Исправлена ​​проблема, из-за которой выполнялась деструктивная миграция, даже если путь миграции был доступен для предварительно упакованной базы данных ( b/432634197 ).

Версия 2.8.0-rc01

13 августа 2025 г.

Выпущен androidx.room:room-*:2.8.0-rc01 . Версия 2.8.0-rc01 содержит следующие коммиты .

Изменения API

  • Удаление устаревших аннотаций @RequiresApi(21) ( Ic4792 , I9103b )

Исправления ошибок

  • Исправлена ​​ошибка, из-за которой Room Flows не выдавал последний результат запроса в ситуации асинхронного множественного запроса/записи. ( Ic9a3c )

Версия 2.8.0-beta01

1 августа 2025 г.

Выпущен androidx.room:room-*:2.8.0-beta01 . Версия 2.8.0-beta01 содержит следующие коммиты .

Исправления ошибок

  • Имена таблиц и представлений теперь корректно экранируются во время деструктивных миграций. ( 9e55f8 , b/427095319 )

Версия 2.8.0-альфа01

16 июля 2025 г.

Выпущена версия androidx.room:room-*:2.8.0-alpha01 . Версия 2.8.0-alpha01 содержит следующие коммиты .

Новые функции

  • Добавлен новый артефакт androidx.room:room-sqlite-wrapper , содержащий API для получения обёртки SupportSQLiteDatabase для RoomDatabase с настроенным SQLiteDriver . Для получения обёртки используйте новую функцию расширения RoomDatabase.getSupportWrapper() . Это артефакт совместимости, позволяющий поддерживать использование SupportSQLiteDatabase , обычно получаемого из RoomDatabase.openHelper.writableDatabase , даже если база данных Room настроена с SQLiteDriver . Эта обёртка полезна для инкрементальной миграции кодовых баз, которые хотят внедрить SQLiteDriver , но при этом активно используют API SupportSQLite , но при этом хотят использовать BundledSQLiteDriver . ( Icf6ac )
  • Добавить цели KMP для Watch OS и TV OS ( I228f6 , b/394238801 )

Исправления ошибок

  • Исправлена ​​взаимоблокировка, которая иногда могла возникать при использовании приостановленных транзакций и AndroidSQLiteDriver . ( b/415006268 )

Версия 2.7

Версия 2.7.2

18 июня 2025 г.

Выпущен androidx.room:room-*:2.7.2 . Версия 2.7.2 содержит следующие коммиты .

Исправления ошибок

  • Исправлена ​​ошибка, из-за которой значения аннотаций неправильно считывались при обработке собственных источников с помощью KSP, иногда отсутствовал экспорт схемы. ( b/416549580 )
  • Исправлена ​​ошибка, из-за которой начальные комментарии в SQL-запросе приводили к выполнению операторов так, как если бы они были нечитаемыми запросами. ( b/413061402 )
  • Исправлена ​​ошибка, из-за которой плагин Gradle от Room не мог настроиться из-за пустого каталога схемы. ( b/417823384 )
  • Исключение SQLiteException больше не генерируется, если получение соединения занимает слишком много времени. Вместо этого библиотека отправляет сообщение в журнал. Ведение журнала вместо отправки исключения позволяет обойти циклы приостановки iOS, из-за чего Room неверно интерпретирует тайм-аут, возникающий в сопрограмме Kotlin при получении соединения, и, таким образом, предотвращает возникновение исключения, когда приложение iOS переходит в фоновый режим и затем возобновляет работу во время операции с базой данных. ( b/422448815 )

Версия 2.7.1

23 апреля 2025 г.

Выпущен androidx.room:room-*:2.7.1 . Версия 2.7.1 содержит следующие коммиты .

Исправления ошибок

  • Исправлена ​​ошибка IndexOutOfBoundsException во время проверки предоставленного преобразователя типов. ( b/409804755 ).
  • Поддерживает RoomDatabase.runInTransaction() , когда SQLiteDriver настроен с Room. ( b/408364828 ).

Версия 2.7.0

9 апреля 2025 г.

Выпущен androidx.room:room-*:2.7.0 . Версия 2.7.0 содержит следующие коммиты .

Важные изменения по сравнению с версией 2.6.0

  • Поддержка Kotlin Multiplatform (KMP): В этом выпуске библиотека Room была переработана и стала библиотекой Kotlin Multiplatform (KMP). В настоящее время поддерживаются следующие платформы: Android, iOS, JVM (для настольных компьютеров), Mac и Linux. Подробнее о начале работы с Room KMP см. в официальной документации по Room KMP . В рамках поддержки KMP Room также можно настроить с помощью SQLiteDriver . Подробнее о миграции существующего приложения на API драйверов и в Room KMP см. в документации по миграции .
  • Генерация кода Kotlin в KSP включена по умолчанию, если обработка выполняется через KSP. Для проектов KAPT или Java Room по-прежнему будет генерировать исходный код Java.
  • Kotlin 2.0 и KSP2: Room теперь ориентирован на язык программирования Kotlin 2.0 и потребует компиляции проектов на Kotlin 2.0 и эквивалентной или более поздней версии. Также добавлена ​​поддержка KSP2, которая рекомендуется при использовании Room с Kotlin 2.0 или более поздней версией.

Версия 2.7.0-rc03

26 марта 2025 г.

Выпущена версия androidx.room:room-*:2.7.0-rc03 . Версия 2.7.0-rc03 содержит следующие коммиты .

Исправления ошибок

  • Больше не выдается исключение InterruptedException , если поток прерывается во время выполнения API блокировки Room, включая блокировку функций DAO ( b/400584611 ).
  • Повторно реализовать пул подключений Room, чтобы попытаться устранить SQLException: Error code: 5, message: Timed out attempting to acquire a reader connection. и аналогичные проблемы ( b/380088809 ).

Версия 2.7.0-rc02

12 марта 2025 г.

Выпущена версия androidx.room:room-*:2.7.0-rc02 . Версия 2.7.0-rc02 содержит следующие коммиты .

Исправления ошибок

  • Исправлена ​​ошибка автоматической миграции, приводившая к неправильной обработке нового столбца в таблице FTS. ( b/348227770 , Ic53f3 )
  • Исправлен сбой компилятора комнат из-за исключения NullPointerException при обработке не-JVM-источников через KSP. ( b/396607230 , I693c9 )
  • Исправлена ​​ошибка, из-за которой Room не делал таблицы недействительными в конце использования соединения с записью. ( b/340606803 , I73ef6 )

Версия 2.7.0-rc01

26 февраля 2025 г.

Выпущен androidx.room:room-*:2.7.0-rc01 . Версия 2.7.0-rc01 содержит следующие коммиты .

Исправления ошибок

  • Исправлена ​​ошибка, из-за которой Room не устанавливал busy_timeout в начальном подключении к базе данных, что приводило к возникновению SQLException: Error code: 5, message: database is locked ( I93208 , b/380088809 ).
  • Исправлена ​​ошибка в компиляторе Room, из-за которой процессор KSP аварийно завершал работу при обработке собственных исходных наборов (например, iOS) на Kotlin 2.1.x и KSP1 ( I883b8 , b/396607230 ).

Версия 2.7.0-beta01

12 февраля 2025 г.

Выпущен androidx.room:room-*:2.7.0-beta01 . Версия 2.7.0-beta01 содержит следующие коммиты .

Исправления ошибок

  • Исправлена ​​проблема с RoomDatabase.inTransaction() при которой открывалась закрытая база данных, когда это недопустимо, и метод должен быстро возвращать false, если база данных закрыта ( b/325432967 ).
  • Исправлен сбой ( IllegalArgumentException: not a valid name ) в компиляторе Room при обработке функций DAO с использованием встроенных классов/классов значений Kotlin ( b/388299754 ).
  • Включите правила Proguard в артефакт JVM room-runtime , чтобы конструктор по умолчанию сгенерированной реализации базы данных не удалялся, поскольку он используется инициализацией Room по умолчанию, которая использует отражение ( b/392657750 ).

Версия 2.7.0-альфа13

29 января 2025 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha13 . Версия 2.7.0-alpha13 содержит следующие коммиты .

Изменения API

  • Room теперь ориентирован на язык Kotlin 2.0 и потребует, чтобы проекты также компилировались с использованием языка Kotlin 2.0 и эквивалентной или более высокой версии языка. ( I8efb0 , b/315461431 , b/384600605 )

Исправления ошибок

  • Исправлена ​​ошибка в конструкторе баз данных Room KMP, из-за которой в Android использовалось простое имя вместо пути, а разрешенный путь к файлу базы данных не находился в каталоге данных приложения. ( I83315 , b/377830104 )
  • Исправлена ​​ошибка в плагине Room Gradle, из-за которой настройка входов и выходов схемы вызывала проблему в проектах Android: property 'inputDirectory' is final and cannot be changed any further. ( 1dbb4c , b/376071291 )
  • Добавлена ​​поддержка KSP2 в плагин Room Gradle, что устраняет проблему, из-за которой каталог схемы не настраивался плагином должным образом. ( Iec3c4 , b/379159770 )

Внешний вклад

  • Исправлена ​​проблема с интеграцией постраничного просмотра Room , приводившая к скачкам пользовательского интерфейса, когда начальная клавиша обновления находилась слишком близко к концу списка. Спасибо, Eva! ( I2abbe , b/389729367 )

Версия 2.7.0-альфа12

11 декабря 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha12 . Версия 2.7.0-alpha12 содержит следующие коммиты .

Изменения API

  • Добавьте экспериментальный API RoomDatabase.Builder.setInMemoryTrackingMode() , чтобы настроить, будет ли Room использовать таблицу в памяти для отслеживания недействительности данных. ( I2a9b2 , b/185414040 )

Исправления ошибок

  • Деструктивные миграции теперь удаляют представления, чтобы гарантировать их повторное создание, согласуя поведение, когда allowDestructiveMigrationForAllTables включен (значение по умолчанию KMP), с существующим поведением, когда он выключен. ( 0a3e83 , b/381518941 )

Версия 2.7.0-альфа11

30 октября 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha11 . Версия 2.7.0-alpha11 содержит следующие коммиты .

Изменения API

  • Пересмотрите недавно добавленную сигнатуру метода convertRows() , чтобы она стала функцией приостановки, которая получает RawRoomQuery для разбиения комнат на страницы. ( Ie57b5 , b/369136627 )

Исправления ошибок

  • Исправлена ​​проблема в подменю комнат, из-за которой генерировался недопустимый код при использовании @Relation совместно с PagingSource .

Версия 2.7.0-альфа10

16 октября 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha10 . Версия 2.7.0-alpha10 содержит следующие коммиты .

Изменения API

  • Создать внутренний класс ByteArrayWrapper для поддержки отношений с ByteBuffer на платформах, отличных от Android и JVM. ( I75543 , b/367205685 )
  • Добавьте SQLiteStatement.getColumnType() вместе с различными константами результата SQLITE_DATA_* , чтобы обеспечить возможность получения типа данных столбца. ( I1985c , b/369636251 )

Версия 2.7.0-альфа09

2 октября 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha09 . Версия 2.7.0-alpha09 содержит следующие коммиты .

Исправления ошибок

  • Исправлена ​​проблема с реализацией KMP room-paging , которая могла привести к Error code: 8, message: attempt to write a readonly database из-за запуска транзакции записи в подключении для чтения. ( b/368380988 )

Версия 2.7.0-альфа08

18 сентября 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha08 . Версия 2.7.0-alpha08 содержит следующие коммиты .

Новые функции

  • Артефакты room-paging были перенесены для совместимости с KMP. ( Ib8756 , b/339934824 )
  • API invalidationTrackerFlow() был распространен как API собственной разработки под названием InvalidationTracker.createFlow() и теперь доступен для исходных наборов, отличных от Android, в проектах KMP. ( I1fbfa , ( I8fb29 ), b/329291639 , b/329315924 )

Изменения API

  • Все предупреждения и сообщения об ошибках в Room, в которых используется слово Cursor , были удалены или заменены, поскольку Cursor больше не является точным общим термином для использования в версии Room для KMP. ( Id8cd9 , b/334087492 )

Исправления ошибок

  • Исправлена ​​проблема, из-за которой Room KMP пытался выдать код с использованием UUID для платформ, отличных от JVM. ( b/362994709 )
  • Исправлена ​​проблема с плагином Room Gradle, которая вызывала ошибку типа «Невозможно изменить атрибуты конфигурации… после того, как она была заблокирована для мутации» при использовании в проекте KMP с Compose Multiplatform. ( b/343408758 )

Версия 2.7.0-альфа07

21 августа 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha07 . Версия 2.7.0-alpha07 содержит следующие коммиты .

Новые функции

  • Плагин Room Gradle теперь автоматически добавляет экспортированные схемы в источники ресурсов Android Instrumentation Test, чтобы их мог использовать MigrationTestHelper .

Исправления ошибок

  • Исправлена ​​проблема с сгенерированным «actual» RoomDatabaseConstructor , из-за которой отсутствовал модификатор «actual» в функции initialize если такая функция также переопределялась в объявлении «expect». ( 359631627 )
  • Исправлена ​​проблема, из-за которой сгенерированное «фактическое» значение RoomDatabaseConstructor не соответствовало видимости объявления «ожидаемое». ( 358138953 )

Версия 2.7.0-альфа06

7 августа 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha06 . Версия 2.7.0-alpha06 содержит следующие коммиты .

Изменения API

  • Измените настройку создания экземпляра RoomDatabase в проекте KMP.

Благодаря модели компиляции Kotlin 2.0 стратегия ссылки на сгенерированную функцию с именем instantiateImpl() больше не актуальна. Представлены два новых API, @ConstructedBy и RoomDatabaseConstructor , которые заменяют стратегию instantiateImpl() . Новая стратегия выглядит следующим образом:

  1. Определить ожидаемый объект, реализующий RoomDatabaseConstructor

      expect object MyDatabaseCtor : RoomDatabaseConstructor<MyDatabase>
    
  2. Свяжите объект с объявлением @Database , используя @ConstructedBy

      @Database(...)
      @ConstructedBy(MyDatabaseCtor::class) // NEW
      abstract class MyDatabase : RoomDatabase
    
  3. Создать новый экземпляр базы данных, но без передачи аргумента фабрики

      fun createNewDatabase(path: String) =
        Room.databaseBuilder<AppDatabase>(name = path)
          .setDriver(BundledSQLiteDriver())
          .setQueryCoroutineContext(Dispatchers.IO)
          .build()
    

Исправления b/316978491 , b/338446862 и b/342905180

  • Поддержка @RawQuery в Room KMP достигается добавлением нового API RoomRawQuery , который похож на SupportSQLiteQuery с точки зрения хранения необработанной строки SQL и функции связывания аргументов с оператором. Аннотированные функции @RawQuery теперь могут принимать RoomRawQuery в качестве единственного параметра. ( Iea844 , b/330586815 )
  • Добавьте перегрузку setQueryCallback() , которая принимает CoroutineContext . ( Id66ff , b/309996304 )
  • Добавлена ​​поддержка целей linuxArm64 Kotlin Multiplatform ( I139d3 , b/338268719 )

Исправления ошибок

  • Исправлена ​​ошибка, из-за которой Room неправильно генерировал вызов recursiveFetchArrayMap на устройствах, отличных от Android. ( 710c36 , b/352482325 )
  • Исправлена ​​ошибка, из-за которой иногда Room выдавал исключение «Превышен интервал ожидания при попытке подключения» в проекте KMP. ( fa72d0 , b/347737870 )
  • Исправлена ​​ошибка в автоматических миграциях, из-за которой проверка внешних ключей выполнялась слишком рано, до того, как другие таблицы изменяли свои схемы в соответствии с новыми внешними ключами. ( 7672c0 , b/352085724 )

Версия 2.7.0-альфа05

10 июля 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha05 . Версия 2.7.0-alpha05 содержит следующие коммиты .

Изменения API

  • Переименован SQLiteKt в SQLite и BundledSQLiteKt в BundledSQLite . ( I8b501 )

Исправления ошибок

  • Исправлена ​​ошибка, из-за которой RoomDatabase блокировалась или возникала ошибка с истечением времени ожидания соединения при использовании AndroidSQLiteDriver .

Версия 2.7.0-альфа04

12 июня 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha04 . Версия 2.7.0-alpha04 содержит следующие коммиты .

Исправления ошибок

  • Исправлена ​​ошибка, из-за которой процессор аннотаций Room генерировал несовместимый код KMP, если в DAO был определен тип возвращаемого значения с несколькими картами. ( b/340983093 )
  • Исправлена ​​ошибка, из-за которой Room не мог найти сгенерированную реализацию базы данных, если аннотированный класс @Database не имел пакета. ( b/342097292 )
  • Исправлена ​​ошибка, из-за которой включение автоматического закрытия и аннулирования нескольких экземпляров иногда приводило к возникновению исключения ConcurrentModificationException , когда база данных автоматически закрывалась из-за бездействия.

Версия 2.7.0-альфа03

29 мая 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha03 . Версия 2.7.0-alpha03 содержит следующие коммиты .

Исправления ошибок

  • Исправлены различные проблемы, связанные с Kotlin 2.0 и KSP 2.0. Обратите внимание, что Kotlin 2.0 с поддержкой KSP 2 ещё не полностью реализован, и команда работает над различными API и изменениями в поведении нового компилятора. ( b/314151707 )

Версия 2.7.0-альфа02

14 мая 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha02 . Версия 2.7.0-alpha02 содержит следующие коммиты .

Исправления ошибок

  • Исправлены различные проблемы с KSP.

Версия 2.7.0-альфа01

1 мая 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha01 . Версия 2.7.0-alpha01 содержит следующие коммиты .

Новые функции

  • Поддержка Kotlin Multiplatform (KMP) : В этом выпуске Room был переработан и стал библиотекой Kotlin Multiplatform (KMP). Несмотря на то, что ещё предстоит проделать некоторую работу, в этом выпуске представлена ​​новая версия Room, в которой большая часть функциональности «унифицирована» (сделана многоплатформенной). В настоящее время поддерживаются Android, iOS, JVM (для настольных компьютеров), Mac и Linux. Любые отсутствующие функции в новых поддерживаемых платформах будут полностью реализованы в следующих выпусках Room.

Более подробную информацию о том, как начать использовать Room KMP, можно найти в официальной документации Room KMP .

  • Генерация кода Kotlin в KSP включена по умолчанию, если обработка выполняется через KSP. Для проектов KAPT или Java Room по-прежнему будет генерировать исходный код Java.

Изменения API

  • Добавлена ​​перегрузка Room.databaseBuilder() , принимающая лямбда-параметр, предназначенный для использования с генерируемой функцией Room, чтобы избежать использования рефлексии при создании экземпляра сгенерированной реализации RoomDatabase . Пример использования:
Room.databaseBuilder<MyDatabase>(
    context = appContext,
    name = dbFilePath,
    factory =  { MyDatabase::class.instantiateImpl() }
)
  • В конструктор добавлен API для настройки Room с использованием CoroutineContext : RoomDatabase.Builder.setQueryCoroutineContext . Обратите внимание, что RoomDatabase можно настроить только с помощью исполнителей, использующих setQueryExecutor , или с использованием контекста Coroutine, но не с помощью обоих методов.
  • Добавлен API для настройки Room с драйвером SQLite : RoomDatabase.Builder.setDriver() . Подробнее об API драйвера SQLite см. в документации SQLite KMP.
  • Добавлены API для доступа к базовому SQLiteConnection из API драйверов: RoomDatabase.useReaderConnection и RoomDatabase.useWriterConnection .
  • Обратные вызовы, связанные с Varios Room, теперь имеют перегруженную версию, которая получает SQLiteConnection вместо SupportSQLiteDatabase . Они предназначены для переопределения при миграции в проект KMP. Подробнее о переносе использования Room из приложения Android в общий модуль KMP см. в руководстве по миграции . Обратные вызовы:
    • Migration.migrate(SQLiteConnection)
    • AutoMigrationSpec.onPostMigrate(SQLiteConnection)
    • RoomDatabase.Callback.onCreate(SQLiteConnection)
    • RoomDatabase.Callback.onDestructiveMigration(SQLiteConnection)
    • RoomDatabase.Callback.onOpen(SQLiteConnection)
  • Артефакт KTX androidx.room:room-ktx был объединён с androidx.room:room-runtime вместе со всеми его API. Артефакт теперь пуст. Пожалуйста, удалите его из списка зависимостей.

Версия 2.6

Версия 2.6.1

29 ноября 2023 г.

Выпущен androidx.room:room-*:2.6.1 . Версия 2.6.1 содержит следующие коммиты.

Исправления ошибок

  • Решена проблема в сгенерированном коде, из-за которой значение по умолчанию для столбцов Double в EntityCursorConverter устанавливалось равным 0 вместо 0,0. Также включено потенциальное исправление аналогичной граничной ситуации для столбцов типа Float. ( Id75f5 , b/304584179 )
  • Исключения, вызванные загрузкой PagingSource , теперь будут передаваться как LoadStateUpdate объекта LoadResult.Error , содержащего Throwable. Это состояние ошибки можно отслеживать с помощью PagingDataAdapter.loadStateFlow(Views) или LazyPagingItems.loadState(Compose) . Обратите внимание, что это знаменует собой изменение поведения: ранее ошибки загрузки всплывали как исключение, вызванное методом dao, который инициировал загрузку. ( I93887 , b/302708983 )

Версия 2.6.0

18 октября 2023 г.

Выпущен androidx.room:room-*:2.6.0 . Версия 2.6.0 содержит следующие коммиты.

Важные изменения по сравнению с версией 2.5.0

  • Возможность включить генерацию кода Kotlin (или «Kotlin CodeGen») теперь доступна в Room KSP ( 4297ec0 ). Чтобы включить Kotlin CodeGen в Room, добавьте имя параметра room.generateKotlin к параметрам процессора для KSP. Подробнее о передаче параметров процессора для KSP см. в документации KSP .

Примечание: При использовании Kotlin CodeGen важно учитывать дополнительные ограничения. Абстрактные свойства, такие как геттеры DAO или запросы DAO в Kotlin CodeGen, запрещены. Вместо этого ожидается, что они будут переписаны как функции, чтобы избежать ложного представления о неизменяемости значения свойства и наличии фиксированного сохранённого результата. Ещё одно добавленное ограничение заключается в том, что в Room for Kotlin CodeGen больше не допускаются возвращаемые типы коллекций, допускающие значение Null.

Предупреждение: при использовании Kotlin CodeGen вы можете обнаружить, что ваши проекты более строги в отношении допустимости значений NULL. В Kotlin CodeGen допустимость значений NULL для аргументов типа важна, тогда как в Java это обычно игнорируется. Например, предположим, что у вас есть `Flow ` возвращает тип, и таблица пуста. В Java CodeGen это не вызовет проблем, но в Kotlin CodeGen вы получите ошибку. Чтобы избежать этого, вам нужно использовать `Flow `, предполагая, что выдается значение null.

  • В Room добавлен новый артефакт для плагина Room Gradle с идентификатором androidx.room , который решает ряд существующих проблем Room, связанных с доступом к входным и выходным данным схем через параметры процессора аннотаций Gradle. Подробнее см. в примечаниях к выпуску Room версии 2.6.0-alpha02 .
  • Классы значений в сущностях комнат теперь поддерживаются для KSP. ( 4194095 )
  • В Room теперь поддерживаются возвращаемые типы вложенных карт в функциях DAO. ( I13f48 , 203008711 )

Версия 2.6.0-rc01

20 сентября 2023 г.

Выпущена версия androidx.room:room-*:2.6.0-rc01 . Версия 2.6.0-rc01 содержит следующие коммиты.

Версия 2.6.0-beta01

23 августа 2023 г.

Выпущена версия androidx.room:room-*:2.6.0-beta01 . Версия 2.6.0-beta01 содержит следующие коммиты.

Исправления ошибок

  • Обработка особого случая исключения SQLite во время обновления и вставки, возникающего, когда во время обновления и вставки возникает исключение 2067 SQLITE_CONSTRAINT_UNIQUE , обновление должно быть выполнено. ( If2849 , b/243039555 )

Версия 2.6.0-альфа03

9 августа 2023 г.

Выпущена версия androidx.room:room-*:2.6.0-alpha03 . Версия 2.6.0-alpha03 содержит следующие коммиты.

Новые функции

  • В Room теперь поддерживаются возвращаемые типы вложенных карт в функциях DAO. ( I13f48 , 203008711 )

Изменения API

  • Была создана новая аннотация типа @MapColumn , которая заменила @MapInfo , которая теперь устарела. Для каждого имени столбца ( keyColumnName , valueColumnName или обоих), указанного в аннотации @MapInfo , необходимо объявить аннотацию @MapColumn только с columnName и использовать аннотацию для конкретного аргумента типа, на который ссылается ссылка (ключ или значение Map) в возвращаемом типе функции DAO. Это связано с тем, что аннотация @MapColumn применяется непосредственно к аргументу типа в возвращаемом типе функции DAO, а не к самой функции, как @MapInfo . Подробнее см. в документации @MapColumn . ( Ib0305 , b/203008711 )
  • Обновлены файлы API для аннотирования подавления совместимости ( I8e87a , b/287516207 ).
  • API плагина Room Gradle были обновлены, чтобы не всегда требовать настройки для каждого варианта. Это означает, что плагин может принимать глобальное расположение для всех вариантов без создания нескольких каталогов, обеспечивая более плавную миграцию, но при этом сохраняя гибкость для ручной настройки вариантов или схем типов сборки, сохраняя при этом все преимущества плагина (воспроизводимые и кешируемые сборки). ( I09d6f , b/278266663 )

Исправления ошибок

  • Исправлена ​​потенциальная уязвимость утечки памяти в QueryInterceptorStatement . ( I193d1 )
  • Исправлено некорректное поведение функции QueryInterceptorDatabase execSQL() . ( Iefdc8 )

Версия 2.6.0-альфа02

21 июня 2023 г.

Выпущена версия androidx.room:room-*:2.6.0-alpha02 . Версия 2.6.0-alpha02 содержит следующие коммиты.

Плагин Room Gradle

В этом новом выпуске содержится новый артефакт для плагина Room Gradle с идентификатором androidx.room , который решает различные существующие проблемы Room, связанные с доступом к входным и выходным данным схем через параметры процессора аннотаций Gradle. Плагин Room Gradle настраивает проект таким образом, чтобы сгенерированные схемы, используемые для автоматической миграции и являющиеся выходными данными задач компиляции, были правильно настроены для создания воспроизводимых и кэшируемых сборок. Плагин предоставляет DSL для настройки расположения базовой схемы:

room {
    schemaDirectory("$projectDir/schemas/")
}

Затем плагин настроит компилятор Room, различные задачи компиляции и его бэкенды (javac, KAPT, KSP) для вывода файлов схемы в папки с разметкой, например, schemas/flavorOneDebug/com.package.MyDatabase/1.json . Как обычно, эти файлы регистрируются в репозитории для проверки и автоматической миграции. При переходе на использование плагина вместо обработчика аннотаций существующие файлы схемы необходимо скопировать в сгенерированные плагином каталоги разметки. Это однократная операция миграции, которую необходимо выполнить вручную. Документация по схеме на сайте developer.android.com будет обновлена ​​после того, как будут рассмотрены все отзывы и плагин станет стабильным, поэтому, пожалуйста, попробуйте.

Изменения API

  • RoomDatabase.QueryCallback определен как функциональный интерфейс, позволяющий использовать преобразование SAM. ( Iab8ea , b/281008549 )

Исправления ошибок

  • Устранена проблема, возникающая при создании экземпляра базы данных в Robolectric после миграции источников Room из Java в Kotlin. ( Ic053c , b/274924903 )

Версия 2.6.0-альфа01

22 марта 2023 г.

Выпущена версия androidx.room:room-*:2.6.0-alpha01 . Версия 2.6.0-alpha01 содержит следующие коммиты.

Новые функции

  • Поддержка классов значений в Room для KSP. Room теперь поддерживает классы значений в Entities. ( 4194095 )
  • Генерацию кода Kotlin (или «Kotlin CodeGen») теперь можно включить в Room ( 4297ec0 ). Чтобы включить Kotlin CodeGen в Room, добавьте имя параметра room.generateKotlin к параметрам процессора для KSP. Подробнее о передаче параметров процессора для KSP см. в документации KSP .

Примечание: При использовании Kotlin CodeGen важно учитывать дополнительные ограничения. Абстрактные свойства, такие как геттеры DAO или запросы DAO в Kotlin CodeGen, запрещены. Вместо этого ожидается, что они будут переписаны как функции, чтобы избежать ложного представления о неизменяемости значения свойства и наличии фиксированного сохранённого результата. Ещё одно добавленное ограничение заключается в том, что в Room for Kotlin CodeGen больше не допускаются возвращаемые типы коллекций, допускающие значение Null.

Предупреждение: при использовании Kotlin CodeGen вы можете обнаружить, что ваши проекты более строги в отношении допустимости значений NULL. В Kotlin CodeGen допустимость значений NULL для аргументов типа важна, тогда как в Java это обычно игнорируется. Например, предположим, что у вас есть `Flow ` возвращает тип, и таблица пуста. В Java CodeGen это не вызовет проблем, но в Kotlin CodeGen вы получите ошибку. Чтобы избежать этого, вам нужно использовать `Flow `, предполагая, что выдается значение null.

Изменения API

  • Защита от бессмысленного использования коллекций, допускающих значение NULL, в возвращаемых типах методов DAO. ( I777dc , b/253271782 , b/259426907 )
  • Добавить API для создания потока, отправляющего изменения в трекер недействительности. API полезен для создания потоков, которые должны реагировать на изменения в базе данных. ( I8c790 , b/252899305 )

Исправления ошибок

  • Запретить абстрактные свойства как геттеры DAO или запросы DAO в кодогенерации Kotlin; вместо этого их следует переписать как функции, чтобы избежать ложного представления о том, что значение свойства неизменяемо и имеет фиксированный сохраненный результат. ( If6a13 , b/127483380 , b/257967987 )

Версия 2.5.2

Версия 2.5.2

21 июня 2023 г.

Выпущен androidx.room:room-*:2.5.2 . Версия 2.5.2 содержит следующие коммиты.

Исправления ошибок

  • Исправлена ​​проблема несовместимости с kotlinx-metadata-jvm. ( 386d5c )
  • Исправлена ​​ошибка, из-за которой Room выдавал ошибку при использовании в тесте Robolectric. ( f79bea , b/274924903 )

Версия 2.5.1

Версия 2.5.1

22 марта 2023 г.

Выпущен androidx.room:room-*:2.5.1 . Версия 2.5.1 содержит следующие коммиты.

Исправления ошибок

  • Избегайте проверки родительского каталога базы данных в FrameworkSQLiteHelper , если база данных уже открыта. ( 5de86b8 )
  • Используйте проверку isOpenInternal при проверке того, открыта ли уже база данных. ( e91fb35 )
  • Теперь доступна улучшенная обработка случая повторного входа в acquireTransactionThread() объекта Room ( 219f98b ). Во время приостанавливаемой транзакции Room использует поток из исполнителя транзакций, запускает в нём цикл событий и отправляет ему приостанавливающие операции с базой данных, чтобы все они были инкапсулированы в сопрограмму транзакции. Обычно ожидается, что поток транзакции отличается от потока, запускающего транзакцию, но в некоторых случаях они совпадают. Для обработки таких случаев повторного входа метод withTransaction() был переработан таким образом, чтобы больше не полагаться на управляющее задание. Вместо этого он выполняет блок приостанавливающей транзакции из runBlocking в потоке транзакции.

Версия 2.5.0

Версия 2.5.0

22 февраля 2023 г.

Выпущены androidx.room:room-paging-guava:2.5.0 , androidx.room:room-paging-rxjava2:2.5.0 и androidx.room:room-paging-rxjava3:2.5.0 . Версия 2.5.0 содержит эти коммиты.

Версия 2.5.0

11 января 2023 г.

Выпущен androidx.room:room-*:2.5.0 . Версия 2.5.0 содержит следующие коммиты.

Важные изменения с версии 2.4.0

  • Все исходные коды room-runtime были преобразованы с Java в Kotlin. Обратите внимание, что вы можете столкнуться с проблемами несовместимости исходного кода, если ваш код написан на Kotlin из-за преобразования библиотеки в Kotlin. Например, известное изменение, связанное с несовместимостью исходного кода, заключается в том, что в InvalidationTracker теперь необходимо объявить onInvalidate() в Observer с параметром типа Set , а не MutableSet . Более того, некоторые методы-геттеры были преобразованы в свойства, требующие синтаксиса доступа к свойствам в файлах Kotlin. Пожалуйста, сообщите об ошибке, если обнаружите какие-либо существенные несовместимости.
  • Добавлена ​​новая аннотация @Upsert , которая пытается вставить сущность, если нет конфликта уникальности, или обновить сущность, если есть конфликт. ( I7aaab , b/241964353 )
  • New room-paging artifacts room-paging-rxjava2 , room-paging-rxjava3 and room-paging-guava have been added for support in Room Paging.
  • Added APIs for providing key and value tables names for disambiguation in @MapInfo ( Icc4b5 )

Version 2.5.0-rc01

7 декабря 2022 г.

androidx.room:room-*:2.5.0-rc01 is released. Version 2.5.0-rc01 contains these commits.

  • This release is identical to 2.5.0-beta02 .

Version 2.5.0-beta02

9 ноября 2022 г.

androidx.room:room-*:2.5.0-beta02 is released. Version 2.5.0-beta02 contains these commits.

Изменения API

  • Fix various APIs that take query arguments from invariant ( Array<Any?> ) to contravariant ( Array<out Any?> ) to match Java's array behavior. ( b/253531073 )

Version 2.5.0-beta01

5 октября 2022 г.

androidx.room:room-*:2.5.0-beta01 is released. Version 2.5.0-beta01 contains these commits.

Изменения API

  • Restrict the minimum version that supports @Upsert to be API 16. This is due to the inability to identity a primary key constraint conflict in older APIs. ( I5f67f , b/243039555 )

Исправления ошибок

  • Fixed an issue where shadow tables where incorrectly exported to the schema .json files, corrupting them. ( I4f83b , b/246751839 )

Version 2.5.0-alpha03

24 августа 2022 г.

androidx.room:room-*:2.5.0-alpha03 is released. Version 2.5.0-alpha03 contains these commits.

Новые функции

  • Added a new shortcut annotation, @Upsert , which attempts to insert an entity when there is no uniqueness conflict or update the entity if there is a conflict. ( I7aaab , b/241964353 )

Исправления ошибок

  • Room will now throw a SQLiteConstraintException instead of a IllegalStateException during an auto-migration foreign key constraint check. ( I328dd )
  • Fix a Kotlin source incompatible change for getter / properties of getOpenHelper , getQueryExecutor and getTransactionExecutor . ( Iad0ac )

Version 2.5.0-alpha02

1 июня 2022 г.

androidx.room:room-*:2.5.0-alpha02 is released. Version 2.5.0-alpha02 contains these commits.

Новые функции

Изменения API

  • All of room-runtime has been converted from Java to Kotlin. ( If2069 , b/206859668 ),( Ie4b55 , b/206859668 ), ( I697ee , b/206859668 ), ( I96c25 , b/206859668 )

    Note: You may encounter source incompatibility issues due to the library conversion to Kotlin. If your code was in Kotlin and calling the old version of Room, the new version will need to handle these cases. For example, a known source incompatible change is that in InvalidationTracker you will now need to declare onInvalidate() in Observer to have a param of type Set and not MutableSet .

  • Added APIs for providing key and value tables names for disambiguation in @MapInfo ( Icc4b5 )
  • Fix a source compatibility issue to re-allow @Ignore in property getters. ( Ifc2fb )

Исправления ошибок

  • Duplicate column resolution heuristic algorithm. Room will now attempt to resolve ambiguous columns in a multimap query. This allows for JOINs with tables containing same-name tables to be correctly mapped to a result data object. ( I4b444 , b/201306012 , b/212279118 )

Version 2.5.0-alpha01

23 февраля 2022 г.

androidx.room:room-*:2.5.0-alpha01 is released. Version 2.5.0-alpha01 contains these commits.

Изменения API

  • Fixed an issue where Room @IntDef usage were not being enforced in Kotlin sources. ( I75f41 , b/217951311 )
  • Fixed a source compatibility issue to re-allow @Query in property getters. ( I0a09b )
  • Converted room-common from Java to Kotlin. ( I69c48 , b/206858235 )

    Note: You may encounter source incompatibility issues as some properties have been moved into companion objects during the library conversion to Kotlin. If your code was in Kotlin and calling the old version of Room, the new version will need the ".Companion" suffix when accessing these properties.

  • Converted room-migration from Java to Kotlin. ( I2724b , b/206858622 )
  • Converted paging related files in room-runtime from Java to Kotlin. ( I82fc8 , b/206859668 )
  • Added API for multi-process lock and usage at the FrameworkSQLite* level, to protect multi-process 1st time database creation and migrations. ( Ied267 , b/193182592 )

Исправления ошибок

  • Added support for internal properties in Kotlin sources. This is a slight behavior change in Room where it will use the source name of functions while matching them to properties as getters/setters (previously, it was using JVM name of the function which is different for internal functions/properties). If you are using custom @JvmName annotations to match getters/setters to private properties, please double check the generated code after the update ( If6531 , b/205289020 )

Версия 2.4.3

Версия 2.4.3

27 июля 2022 г.

androidx.room:room-*:2.4.3 is released. Version 2.4.3 contains these commits.

Исправления ошибок

  • Fixed an issue that would cause Room to not recognize suspend functions in Kotlin 1.7 ( b/236612358 )

Версия 2.4.2

Версия 2.4.2

23 февраля 2022 г.

androidx.room:room-*:2.4.2 is released. Version 2.4.2 contains these commits.

Исправления ошибок

  • Fix an issue generating code for a Dao @Transaction suspend function with a body that generates a default interface method due to compilation with -Xjvm-default=all or equivalent. ( Ia4ce5 )
  • Resolving a bug where Room generates code for a Array<ByteArray> return type query method. ( If086e , b/213789489 )

Версия 2.4.1

Версия 2.4.1

12 января 2022 г.

androidx.room:room-*:2.4.1 is released. Version 2.4.1 contains these commits.

Исправления ошибок

  • Added support for internal properties in Kotlin sources. This is a slight behavior change in Room where it will use the source name of functions while matching them to properties as getters/setters (previously, it was using JVM name of the function which is different for internal functions/properties). If you are using custom @JvmName annotations to match getters/setters to private properties, please double check the generated code after the update ( If6531 , b/205289020 )

Версия 2.4.0

Версия 2.4.0

15 декабря 2021 г.

androidx.room:room-*:2.4.0 is released. Version 2.4.0 contains these commits.

Important changes since 2.3.0

  • Auto Migrations : Room now offers an API for automatically generating migrations as long as schemas are exported. To let Room know that it should generate an auto-migration a new property @Database#autoMigrations can be used to declare the versions to auto-migrate from and to. When Room needs additional information regarding tables and column renames or deletes, then the @AutoMigration annotation can declare a specification class containing such inputs. See the @AutoMigration documentation for more details.
  • Dependency Injection in Auto Migrations : @ProvidedAutoMigrationSpec is a new API for declaring that an AutoMigrationSpec will be provided at runtime via RoomDatabase.Builder#addAutoMigrationSpec() . This allows for a dependency injection framework to provide such specs when they need complex dependencies.
  • Migration Test Helper Support for Auto Migrations : Room's MigrationTestHelper was updated to support auto migrations by providing a new constructor API that receives the database class under test. This allows the helper to automatically add auto migrations the same way during runMigrationsAndValidate .
  • Room-Paging Support : androidx.room:room-paging is released, providing native Paging 3.0 support for Room queries returning androidx.paging.PagingSource .
  • Relational Query Methods : Room now supports multimap return types @Dao methods, useful for JOIN statements. The supported types of multimaps are Map , SparseArray , LongSparseArray , along with Guava's ImmutableMap , ImmutableSetMultimap and ImmutableListMultimap .

Version 2.4.0-rc01

1 декабря 2021 г.

androidx.room:room-*:2.4.0-rc01 is released. Version 2.4.0-rc01 contains these commits.

Новые функции

  • Update Room's dependency on KSP to 1.6.0-1.0.1 to support Kotlin 1.6

Version 2.4.0-beta02

17 ноября 2021 г.

androidx.room:room-*:2.4.0-beta02 is released. Version 2.4.0-beta02 contains these commits.

Новые функции

  • We've added support for SparseArray and LongSparseArray in @MapInfo. ( Ic91a2 b/138910317 )

Исправления ошибок

  • We've added a new TypeConverter analyzer that takes nullability information in types into account. As this information is only available in KSP, it is turned on by default only in KSP. If it causes any issues, you can turn it off by passing room.useNullAwareTypeAnalysis=false to the annotation processor. If that happens, please a file bug as this flag will be removed in the future. With this new TypeConverter analyzer, it is suggested to only provide non-null receiving TypeConverters as the new analyzer has the ability to wrap them with a null check. Note that this has no impact for users using KAPT or Java as the annotation processors (unlike KSP), don't have nullability information in types. ( Ia88f9 , b/193437407 )
  • Fix a bug where Room would fail to compile with a SQL error when an FTS entity declared to use the ICU tokenizer. ( I00db9 , b/201753224 )
  • Resolved issue in auto migrations regarding a new column added to an embedded Entity between versions. ( I5fcb1 b/193798291 )
  • We have resolved an issue regarding the relational query method return types in LEFT JOIN queries. With these changes, in the case where a 1-many mapping is present, the collection returned for a key will not include the invalid value object if it is not found in the cursor. If no valid values are found, then a key will be mapped to an empty collection. ( Id5552 b/201946438 )
  • Resolved the auto migration issue where SQLite keywords failed to be escaped in column names. ( Idbed4 b/197133152 )

Version 2.4.0-beta01

13 октября 2021 г.

androidx.room:room-*:2.4.0-beta01 is released. Version 2.4.0-beta01 contains these commits.

Исправления ошибок

  • Fixed an issue with auto-migrations not adding new columns when another table in the same auto-migration also had a new column with the same name. ( Ia5db5 , b/200818663 )
  • The PagingSource implementation generated by room-paging now uses the queryExecutor passed through RoomDatabase.Builder , so it can be overridden, instead of Dispatchers.IO previously. ( Iae259 )

Version 2.4.0-alpha05

29 сентября 2021 г.

androidx.room:room-*:2.4.0-alpha05 is released. Version 2.4.0-alpha05 contains these commits.

Новые функции

Изменения API

  • Added a new property to the TypeConverters annotation to let developers disable built-in Enum and UUID converters. By default, these converters are on but you can disable them for a certain scope, or for the whole database. See TypeConverters documentation for details. ( 36ae9e , b/195413406 )

  • Supporting non-POJO keys/values for Multimap return types in DAOs via the @MapInfo annotation. ( I4d704 )

@MapInfo will be required when the key or value column of the map are from a single column. See example:

@MapInfo(valueColumn = "songCount")
@Query("""
       SELECT *, COUNT(mSongId) as songCount
       FROM Artist JOIN Song ON Artist.artistName = Song.artist
       GROUP BY artistName
       """)
fun getArtistAndSongCounts(): Map<Artist, Integer>
  • Make room-paging a required artifact when using Paging3 with Room. ( Ieaffe )

Исправления ошибок

  • Fix an issue where multimap queries results were not correctly ordered when the query contained an ORDER BY clause of a column from the map's key. ( I6b887 )

Внешний вклад

  • Added new API to specify index order in @Index. Thanks to Nikita Zhelonkin. ( I033fc )

Version 2.4.0-alpha04

21 июля 2021 г.

androidx.room:room-*:2.4.0-alpha04 is released. Version 2.4.0-alpha04 contains these commits.

Новые функции

  • Room now supports multimap return types @Dao methods, useful for JOIN statements. The supported types of multimaps are Map along with Guava's ImmutableMap , ImmutableSetMultimap and ImmutableListMultimap .

    The following are examples of multimap queries:

    One-to-One Relation Map

    @Query("SELECT * FROM Song JOIN Artist ON Song.artistId = Artist.artistId")
    fun getSongAndArtist(): Map<Song, Artist>
    

    One-to-Many Relation Map (Standard multimap)

    @Query("SELECT * FROM Artist JOIN Album ON Artist.id = Album.artistId")
    fun getArtistAndAlbums(): Map<Artist, List<Album>>
    

    The multimap result can also be wrapped in the supported async return types, such as LiveData , Rx's Observable , or coroutines Flow .

Room-Paging

  • androidx.room:room-paging is released, providing native Paging 3.0 support for Room queries returning androidx.paging.PagingSource .

    @Dao
    interface UserDao {
      @Query("SELECT * FROM users ORDER BY id ASC")
      fun loadUsers(): PagingSource<Int, User>
    }
    
  • This artifact replaces the androidx.paging.PagingSource implementation generated by Room with one built on top of Paging 3.0 APIs. The new PagingSource implementation parses keys differently, so any key manually supplied to Room's PagingSource would need to account for this behavior change, including the initialKey passed via Pager's constructor. Pages will start loading from the Key with Key being the first loaded item. This deviates from existing behavior where LoadParams.Refresh.Key is treated as the user's scroll position and items are loaded both before and after the key.

  • The artifact is optional and opting out will fallback to existing support for Paging 3.0 that was introduced in Room 2.3. However, this artifact will become non-optional in future release for those using Room with Paging 3.0. To opt-in, add the new room-paging artifact to your classpath. If you are using Gradle, you can add the following snippet to your build.gradle:

    dependency {
      implementation("androidx.room:room-paging:2.4.0-alpha04")
    }
    

Исправления ошибок

  • Fix an issue in auto migrations regarding handling foreign key violations. ( b/190113935 )

Version 2.4.0-alpha03

16 июня 2021 г.

androidx.room:room-*:2.4.0-alpha03 is released. Version 2.4.0-alpha03 contains these commits.

Изменения API

  • Update Room's MigrationTestHelper to support auto migrations by providing a new constructor API that receives the database class under test. This allows the helper to automatically add auto migrations the same way during runMigrationsAndValidate .

Исправления ошибок

  • Fixed an issue with Room's SQLite native library to support Apple's M1 chips. ( b/174695268

  • Fixed an issue where Room would not error out when the return type of a @Transaction function was a Flow ( I56ddd , b/190075899 )

  • Fix an issue in auto migrations regarding indices. b/177673291

Обновления зависимостей

  • Room's KSP support now depends on KSP 1.5.10-1.0.0-beta01 . ( 1ecb11 , b/160322705 )

Version 2.4.0-alpha02

5 мая 2021 г.

androidx.room:room-*:2.4.0-alpha02 is released. Version 2.4.0-alpha02 contains these commits.

Изменения API

  • @ProvidedAutoMigrationSpec is a new API for declaring that an AutoMigrationSpec will be provided at runtime via RoomDatabase.Builder#addAutoMigrationSpec() . This allows for a dependency injection framework to provide such specs when they need complex dependencies.

Исправления ошибок

  • Fix an issue with auto migrations where @DatabaseView s where not being properly re-created.

Внешний вклад

  • Fix an issue in Room's JournalMode.TRUNCATE where the InvalidationTracker callback was sometimes being invoked invalidly, too late, or not at all. Thanks to Uli Bubenheimer | bubenheimer@users.noreply.github.com ( b/154040286 )

Version 2.4.0-alpha01

21 апреля 2021 г.

androidx.room:room-*:2.4.0-alpha01 is released. Version 2.4.0-alpha01 contains these commits.

Новые функции

  • Auto Migrations : Room now offers an API for automatically generating migrations as long as schemas are exported. To let Room know that it should generate an auto-migration a new property @Database#autoMigrations can be used to declare the versions to auto-migrate from and to. When Room needs additional information regarding tables and column renames or deletes, then the @AutoMigration annotation can declare a specification class containing such inputs. See the @AutoMigration documentation for more details.

Исправления ошибок

  • Fix an issue where defaultValue with extra parenthesis were being incorrectly validated by Room's schema validation. b/182284899

Версия 2.3.0

Версия 2.3.0

21 апреля 2021 г.

androidx.room:room-*:2.3.0 is released. Version 2.3.0 contains these commits.

Important changes since 2.2.0

  • Built-in Enum Support : Room will now default to using an Enum to String and vice versa type converter if none is provided. If a type converter for an enum already exists, Room will prioritize using it over the default one.
  • Query Callback : Room now offers a general callback API RoomDatabase.QueryCallback, for when queries are about to execute, which can be useful for logging in debug builds. The callback can be set via RoomDatabase.Builder#setQueryCallback() .
  • Pre-packaged Improvement : Room now has APIs for creating a database using a pre-packaged database read from an input stream. This allows for cases such as when the pre-package database is gzipped.
  • Provided Type Converters : Room now has APIs for providing instances of type converters such that the app can control their initialization. To mark a type converter that will be provided to Room use the new annotation @ProvidedTypeConverter.
  • RxJava3 Support : Room now supports RxJava3 types. Similar to RxJava2 you can declare DAO methods whose return type are Flowable, Single, Maybe and Completable. Additionally a new artifact androidx.room:room-rxjava3 is available to support RxJava3.
  • Paging 3.0 Support : Room will now support generating implementations for @Query annotated methods whose return type is androidx.paging.PagingSource .

Version 2.3.0-rc01

24 марта 2021 г.

androidx.room:room-*:2.3.0-rc01 is released. Version 2.3.0-rc01 contains these commits.

Исправления ошибок

  • Fix an issue that prevented Coroutine Flow queries created by Room to be consumed in a suspending withTransaction block. ( I797bf )

Version 2.3.0-beta03

10 марта 2021 г.

androidx.room:room-*:2.3.0-beta03 is released. Version 2.3.0-beta03 contains these commits.

Новые функции

Исправления ошибок

  • Fixed a bug where creating PagingSource on the main thread could trigger an ANR. ( I42b74 , b/181221318 )
  • Fixed @ExperimentalRoomApi visibility to be public instead of package private. ( b/181356119 )

Внешний вклад

  • Allow Room to accept a POJO return type in a @Query annotated DAO method when it is also annotated with @SkipQueryVerification . Room will do a best-effort to convert the result of the query to the POJO return type the same way it is done for a @RawQuery annotated DAO method. Thanks to 'Markus Riegel | hey@marcorei.com'. ( I45acb )

Version 2.3.0-beta02

18 февраля 2021 г.

androidx.room:room-*:2.3.0-beta02 is released. Version 2.3.0-beta02 contains these commits.

Новые функции

  • Room now has experimental support for Kotlin Symbol Processing KSP .

    KSP is a replacement for KAPT to run annotation processors natively on the Kotlin compiler, significantly reducing build times.

    To use Room with KSP, you can apply the KSP Gradle plugin and replace the kapt configuration in your build file with ksp . For example, instead of kapt 'androidx.room:room-compiler:2.3.0-beta02' use ksp 'androidx.room:room-compiler:2.3.0-beta02' . See the KSP documentation for more details.

    Note that since KSP is experimental, it is recommended to still use KAPT for production code. The reduction of build times is only applicable if there are no other processors that use KAPT. See b/160322705 for known issues.

Version 2.3.0-beta01

27 января 2021 г.

androidx.room:room-*:2.3.0-beta01 is released. Version 2.3.0-beta01 contains these commits.

Новые функции

  • Auto Closable Databases : Room now has the ability to close databases that are not accessed after a given amount of time. This is an experimental feature and can be enabled by calling RoomDatabase.Builder#setAutoCloseTimeout() . This feature is useful for applications with multiple databases.

Исправления ошибок

  • Fix an issue where Dao methods with multiple @Update or @Delete methods with different conflict strategies would generate code with only one of the strategies, effectively ignoring the defined one. ( /I0b90d , b/176138543 )

Version 2.3.0-alpha04

16 декабря 2020 г.

androidx.room:room-*:2.3.0-alpha04 is released. Version 2.3.0-alpha04 contains these commits.

Новые функции

  • Room now offers a general callback API RoomDatabase.QueryCallback , for when queries are about to execute, which can be useful for logging in debug builds. The callback can be set via RoomDatabase.Builder#setQueryCallback() . ( Iaa513 , b/174478034 , b/74877608 )
  • Room will now default to using an Enum to String and vice versa type converter if none is provided. If a type converter for an enum already exists, Room will prioritize using it over the default one. ( b/73132006 )

Известная проблема

  • If a one-way type converter for reading already exists for the Enum, Room might accidentally use the built-in String to Enum converter which might not be desired. This is a known issue and can be fixed by making it a two-way converter. See: b/175707691

Исправления ошибок

  • Fixed an issue where Room would incorrectly disabled incremental annotation processing in newer JDK versions. ( b/171387388 )
  • Fixed an issue with Room finding the generated class when multiple class loaders are used. Thanks for the fix 'Serendipity | 892449346@qq.com'! ( b/170141113 )
  • Fixed an issue where Room would generate incorrect code when a Kotlin @Dao had a base class whose generics are primitives in the JVM. ( b/160258066 )

Внешний вклад

  • Room will now default to using beginTransactionNonExclusive if WAL mode is enabled and API is 16 or more. Thanks to 'Ahmed I. Khalil | ahmedibrahimkhali@gmail.com'! ( b/126258791 )

Version 2.3.0-alpha03

14 октября 2020 г.

androidx.room:room-*:2.3.0-alpha03 is released. Version 2.3.0-alpha03 contains these commits.

Новые функции

  • Room now has APIs for providing instances of type converters such that the app can control their initialization. To mark a type converter that will be provided to Room use the new annotation @ProvidedTypeConverter . Thanks to 'mzgreen yairobbe@gmail.com '. ( Ie4fa5 , b/121067210 )

  • Room now has APIs for creating a database using a pre-packaged database read from an input stream. This allows for cases such as when the pre-package database is gzipped. Thanks to 'Ahmed El-Helw ahmedre@gmail.com ' ( 3e6792 , b/146911060 )

Изменения API

  • Added missing target to @ForeignKey annotation preventing its usage outside of the @Entity annotation. ( Iced1e )

  • The field mCallbacks in RoomDatabase.java is now hidden. ( d576cb , b/76109329 )

Исправления ошибок

  • Update to TypeConverters documentation to clarify that TypeConverters can only be used to convert columns / fields and not rows. ( I07c56 , b/77307836 )

  • Update to the DaoProcessor to fix compiler error on Dao with a generic super type with Kotlin "primitives". ( Ice6bb , b/160258066 )

  • Update add/remove observer methods documentation to clarify threading ( Ifd1d9 , b/153948821 )

  • Fix an issue with Room incorrectly validating FTS tables that declared their rowid column. ( d62ebc , b/145858914 )

External Contributions

  • Fix upper/lowercase locale issues related to Turkish ( 5746e3 ), b/68159494

  • Replace the ConcurrentHashMap inside RoomDatabase with Collections.synchronizedMap() to avoid issues on Android Lollipop ( d1cfc7 , b/162431855 )

  • Add a onOpenPrepackagedDatabase callback for when a prepackaged DB is copied. ( I1ba74 , b/148934423 )

Version 2.3.0-alpha02

22 июля 2020 г.

androidx.room:room-*:2.3.0-alpha02 is released. Version 2.3.0-alpha02 contains these commits.

Новые функции

  • RxJava3 Support : Room now supports RxJava3 types. Similar to RxJava2 you can declare DAO methods whose return type are Flowable, Single, Maybe and Completable. Additionally a new artifact androidx.room:room-rxjava3 is available to support RxJava3. ( b/152427884 )

Изменения API

  • Declaring a @TypeConverter in Kotlin Object class is now supported. ( b/151110764 )
  • Room incremental annotation processing option is now ON by default. ( b/112110217 )

Version 2.3.0-alpha01

10 июня 2020 г.

androidx.room:room-*:2.3.0-alpha01 is released. Version 2.3.0-alpha01 contains these commits.

Новые функции

  • Paging 3.0 Support : Room will now support generating implementations for @Query annotated methods whose return type is androidx.paging.PagingSource .

    @Dao
    interface UserDao {
      @Query("SELECT * FROM users ORDER BY id ASC")
      fun pagingSource(): PagingSource<Int, User>
    }
    

Изменения API

  • @RewriteQueriesToDropUnusedColumns is a new convenient annotation that makes Room rewrite the '*' projection in a query such that unused columns in the result are removed.
  • The processor option room.expandProjection is now deprecated. Use @RewriteQueriesToDropUnusedColumns as a replacement for Room optimizing queries with star projections. Note that @RewriteQueriesToDropUnusedColumns does not replace the column conflict solution room.expandProjection offered with regards to return types that contained @Embedded fields.

Исправления ошибок

  • Fixed a bug where Room would not correctly detect the JDK version used to enable incremental annotation processor. Thanks to Blaz Solar (me@blaz.solar) ( b/155215201 )
  • Room now embeds its ANTLR dependency with the annotation processor to avoid version conflicts with other processors that also use ANTLR. ( b/150106190 )

Version 2.2.6

Version 2.2.6

16 декабря 2020 г.

androidx.room:room-*:2.2.6 is released. Version 2.2.6 contains these commits.

Исправления ошибок

  • Fixed an issue where Room would incorrectly disabled incremental annotation processing in newer JDK versions. ( b/171387388 )

Версия 2.2.5

Версия 2.2.5

18 марта 2020 г.

androidx.room:room-*:2.2.5 is released. Version 2.2.5 contains these commits.

Исправления ошибок

  • Make MultiInstanceInvalidationService directBootAware. Thanks to 'Mygod contact-git@mygod.be ' ( b/148240967 )
  • Fixed a bug that would cause a crash when multi-instance invalidation was enabled and the database contained a FTS entity. ( b/148969394 )
  • Fixed an issue when loading the SQLite native libraries in the Room annotation processor that would cause the compiler to crash due to parallel compilations. ( b/146217083 )

Версия 2.2.4

Версия 2.2.4

19 февраля 2020 г.

androidx.room:room-common:2.2.4 , androidx.room:room-compiler:2.2.4 , androidx.room:room-guava:2.2.4 , androidx.room:room-ktx:2.2.4 , androidx.room:room-migration:2.2.4 , androidx.room:room-runtime:2.2.4 , androidx.room:room-rxjava2:2.2.4 , and androidx.room:room-testing:2.2.4 are released. Version 2.2.4 contains these commits.

Исправления ошибок

  • Fixed an issue with suspending transactions where they would deadlock if the coroutine was canceled quickly before the transaction actually started. ( b/148181325 )
  • Fixed an issue with the @Generated being wrongly used when building with JDK 9. ( b/146538330 )
  • Fixed an issue where Room would generate incorrect code when a DAO interface in Kotlin had a concrete function. ( b/146825845 )

Версия 2.2.3

Версия 2.2.3

18 декабря 2019 г.

androidx.room:room-*:2.2.3 is released. Version 2.2.3 contains these commits .

Исправления ошибок

  • Fixed a bug where Room would fail to validate a database that had not gone through any migration and contained a legacy hash with indices in its schema. ( b/139306173 )

Версия 2.2.2

Версия 2.2.2

20 ноября 2019 г.

androidx.room:room-*:2.2.2 is released. Version 2.2.2 contains these commits .

Исправления ошибок

  • Fixed a bug where collecting a one-to-one relationship with more than 999 rows would cause Room to return null relating items. ( b/143105450 )

Версия 2.2.1

Версия 2.2.1

23 октября 2019 г.

androidx.room:room-*:2.2.1 is released. Version 2.2.1 contains these commits .

Исправления ошибок

  • Fixed a bug where Room would incorrectly warn about CURSOR_MISMATCH with the compiler option expandProjection turned ON. ( b/140759491 )
  • Added a retry mechanism for handling the missing native library used for verifying queries during compile time.

Версия 2.2.0

Версия 2.2.0

9 октября 2019 г.

androidx.room:room-*:2.2.0 is released. Version 2.2.0 contains these commits .

Important changes since version 2.1.0

  • Pre-packaged Database : Two new APIs in RoomDatabase.Builder are now available for creating a RoomDatabase given an already populated database file. createFromAsset() is for when the pre-populated database file is in the assets folder of the APK, while createFromFile() is for when the file is in an arbitrary location. The usages of these API change the behaviour of destructive migrations such that during a fallback migration, Room will try to re-copy the pre-populated database if available, otherwise it fallbacks to just dropping and re-creating all tables. b/62185732
  • Schema Default Values : @ColumnInfo now has a new property defaultValue that can be used to specify the default value of a column. Default values are part of a database schema and will be validated during migrations if specified. b/64088772
  • Many-to-Many Relations : @Relation now has a new property associateBy , that takes in a new annotation @Junction , used to declare a relation that needs to be satisfied via a junction table (also known as a join table). b/69201917
  • One-to-One Relations : The restriction in POJO fields annotated with @Relation to be of type List or Set has been lifted, effectively allowing single-value relations to be represented. b/62905145
  • Target Entity : The DAO annnotations @Insert , @Update and @Delete now has a new property targetEntity , that allows specifying the target table the DAO method is meant to act on. This allows for the parameters of those DAO methods to be arbitrary POJOs which will be interpreted as partial entities. In practice, this allows partial inserts, deletes and updates. b/127549506
  • Coroutines Flow : @Query DAO methods can now be of return type Flow<T> . The returned Flow will re-emit a new set of values if the observing tables in the query are invalidated. Declaring a DAO function with a Channel<T> return type is an error, Room instead encourages you to use Flow and then use the neighboring functions to convert the Flow into a Channel . b/130428884
  • Gradle Incremental Annotation Processor : Room is now a Gradle isolating annotation processor and incrementability can be enabled via the processor option room.incremental . See Room Compiler Options for more information. If you encounter any issues please file a bug here . We plan to enable incrementability by default in a future, stable version. b/112110217
  • Expanding Projections : A new experimental compiler option room.expandProjection was added that causes Room to rewrite a query with a star projection to only contain the columns in the returning type POJO. For example, for a DAO method with @Query("SELECT * FROM Song") that returns a POJO named SongIdAndTitle with only two fields. Then Room will rewrite the query to SELECT id, title FROM Song such that the minimum set of columns to satisfy the return type are fetched. This essentially eliminates the CURSOR_MISMATCH warning that is presented when the query returns extra columns that do not match any field in the returning POJO type.

Version 2.2.0-rc01

5 сентября 2019 г.

androidx.room:room:2.2.0-rc01 is released. The commits included in this version can be found here .

No public changes since Room 2.2.0-beta01 .

Version 2.2.0-beta01

22 августа 2019 г.

androidx.room:room-*:2.2.0-beta01 is released. The commits included in this version can be found here .

Исправления ошибок

  • Fixed a bug where a Coroutine Flow query would stop reemitting new values after a certain time. ( b/139175786 )
  • Fixed a bug where Room would not accept a legacy schema hash code while opening a database that had not gone a migration since Room 1.0, causing a runtime crash due to invalid schema. ( b/139306173 )

Version 2.2.0-alpha02

7 августа 2019 г.

androidx.room:room-*:2.2.0-alpha02 is released. The commits included in this version can be found here .

Новые функции

  • Coroutines Flow : @Query DAO methods can now be of return type Flow<T> . The returned Flow will re-emit a new set of values if the observing tables in the query are invalidated. Declaring a DAO function with a Channel<T> return type is an error, Room instead encourages you to use Flow and then use the neighboring functions to convert the Flow into a Channel . b/130428884
  • Expanding Projections : A new experimental compiler option room.expandProjection was added that causes Room to rewrite a query with a star projection to only contain the columns in the returning type POJO. For example, for a DAO method with @Query("SELECT * FROM Song") that returns a POJO named SongIdAndTitle with only two fields. Then Room will rewrite the query to SELECT id, title FROM Song such that the minimum set of columns to satisfy the return type are fetched. This essentially eliminates the CURSOR_MISMATCH warning that is presented when the query returns extra columns that do not match any field in the returning POJO type.
  • onDestructiveMigrate is a new callback API added to RoomDatabase.Callback for when Room destructively migrates a database. b/79962330

Исправления ошибок

  • Fixed a bug where Room would generate incorrect code using a method as field setter when the field is protected. b/136194628
  • Fixed a bug that caused the InvalidationTracker to throw a NPE in a second process when multi-instance invalidation was enabled and the invalidation Service was killed. b/137454915
  • Fixed a bug where Room would not correctly identify the return type of an inherited suspend function annotated with @RawQuery . b/137878827
  • Updated the generated code for @Relation when the relating key is of type BLOB to use a ByteBuffer that is comparable. b/137881998
  • Fixed a bug where Room would complain about missing setters on POJOs used as partial entity parameters of @Insert , @Update and @Delete . b/138664463
  • Fixed a bug where Room would complain about missing getters & setters for an ignored column via @Entity when the entity class was used in certain DAO methods. b/138238182
  • Fixed a bug where Room would not correctly convert named binding args to positional args causing a runtime exception when executing a query with re-used parameters. b/137254857

Version 2.2.0-alpha01

10 июля 2019 г.

Новые функции

  • Pre-packaged Database : Two new APIs in RoomDatabase.Builder are now available for creating a RoomDatabase given an already populated database file. createFromAsset() is for when the pre-populated database file is in the assets folder of the APK, while createFromFile() is for when the file is in an arbitrary location. The usages of these API change the behaviour of destructive migrations such that during a fallback migration, Room will try to re-copy the pre-populated database if available, otherwise it fallbacks to just dropping and re-creating all tables. b/62185732
  • Schema Default Values : @ColumnInfo now has a new property defaultValue that can be used to specify the default value of a column. Default values are part of a database schema and will be validated during migrations if specified. b/64088772

    Note: If your database schema already has default values, such as those added via ALTER TABLE x ADD COLUMN y INTEGER NOTNULL DEFAULT z , and you decide to define default values via @ColumnInfo to the same columns, then you might need to provide a migration to validate the unaccounted default values. See Room Migrations for more information.

  • Many-to-Many Relations : @Relation now has a new property associateBy , that takes in a new annotation @Junction , used to declare a relation that needs to be satisfied via a junction table (also known as a join table). b/69201917
  • One-to-One Relations : The restriction in POJO fields annotated with @Relation to be of type List or Set has been lifted, effectively allowing single-value relations to be represented. b/62905145
  • Target Entity : The DAO annnotations @Insert , @Update and @Delete now has a new property targetEntity , that allows specifying the target table the DAO method is meant to act on. This allows for the parameters of those DAO methods to be arbitrary POJOs which will be interpreted as partial entities. In practice, this allows partial inserts, deletes and updates. b/127549506
  • Gradle Incremental Annotation Processor : Room is now a Gradle isolating annotation processor and incrementability can be enabled via the processor option room.incremental . See Room Compiler Options for more information. If you encounter any issues please file a bug here . We plan to enable incrementability by default in a future, stable version. b/112110217

Исправления ошибок

  • Room will no longer propagate the EmptySetResultException to the global error handler when the Rx stream of a query has been disposed before the query is complete. b/130257475
  • Fixed a bug where Room would show an incorrect error message when a suspend DAO function annotated with @RawQuery didn't have a return type. b/134303897
  • Room will no longer generate DAO adapters with raw types. b/135747255

Версия 2.1.0

Версия 2.1.0

13 июня 2019 г.

Room 2.1.0 is released with no changes from 2.1.0-rc01 . The commits included in the version can be found here .

Important changes since 2.0.0

  • FTS : Room now supports entities with a mapping FTS3 or FTS4 table. Classes annotated with @Entity can now be additionally annotated with @Fts3 or @Fts4 to declare a class with a mapping full-text search table. FTS options for further customization are available via the annotation's methods.
  • Views : Room now supports declaring a class as a stored query, also known as a view , using the @DatabaseView annotation.
  • Couroutines : DAO methods can now be suspend functions. Include room-ktx in your dependencies to take advantage of this functionality. The ktx artifact also provides the extension function RoomDatabase.withTransaction for performing database transactions within a coroutine.
  • Auto Value : Room now supports declaring AutoValue annotated classes as entities and POJOs. The Room annotations @PrimaryKey , @ColumnInfo , @Embedded and @Relation can now be declared in an auto value annotated class's abstract methods. Note that these annotation must also be accompanied by @CopyAnnotations for Room to properly understand them.
  • Additional Async Support : DAO methods annotated with @Insert , @Delete or @Update , along with @Query containing INSERT , DELETE or UPDATE statements, now support Rx return types Completable , Single , Maybe , and Guava's return type ListenableFuture , and they can also be suspend functions.
  • enableMultiInstanceInvalidation is a new API in RoomDatabase.Builder to enable invalidation across multiple instances of RoomDatabase using the same database file.
  • fallbackToDestructiveMigrationOnDowngrade is a new API in RoomDatabase.Builder to automatically re-create the database if a downgrade happens.
  • ignoredColumns is a new API in the @Entity annotation that can be used to list ignored fields by name.
  • Room will now properly use Kotlin's primary constructor in data classes avoiding the need to declare the properties as vars .

Version 2.1.0-rc01

29 мая 2019 г.

Исправления ошибок

  • Fixed a Room initialization error that might occur due to an already setup temp_store configuration. b/132602198
  • Fixed a double quote usage warning for users with SQLite 3.27.0 and above. b/131712640
  • Fixed a bug where the InvalidationTracker would cause a crash when multiple invalidation checks would occur in parallel. b/133457594

Version 2.1.0-beta01

7 мая 2019 г.

androidx.room 2.1.0-beta01 is released with no changes from 2.1.0-alpha07. The commits included in this version can be found here .

Version 2.1.0-alpha07

25 апреля 2019 г.

API / Behavior Changes

  • The extension function RoomDatabase.withTransaction has been changed to no longer take a function block with a CoroutineScope as receiver. This prevents skipping the additional coroutineScope { } wrapper required to run things in the transaction block concurrently.

Исправления ошибок

  • Fixed a bug where Room would fail to match a TypeConverter for a Kotlin DAO function containing a parameter of Collection type. b/122066791

Version 2.1.0-alpha06

22 марта 2019 г.

API / Behavior Changes

  • Async transaction queries are now serialized such that Room will not use more than one thread for executing database transactions. RoomDatabase.Builder.setTransactionExecutor(Executor) was added to allow configuring the executor to be used for transactions.
  • RoomDatabase.runInTransaction(Callable) will no longer wrap checked exceptions into RuntimeExceptions. b/128623748

Исправления ошибок

  • Fixed a bug where the invalidation tracker would stop observing a content table if observers for both the content table and an external content FTS table were added. b/128508917
  • Updated Room SQLite grammar to match SQLite 3.24.0. b/110883668

Version 2.1.0-alpha05

13 марта 2019 г.

Новые функции

  • The extension function RoomDatabase.withTransaction allows you to safely perform database transactions within a coroutine. Room extensions functions along with coroutines support are available in the room-ktx artifact.
  • Non-abstract DAO methods annotated with @Transaction can now be suspend functions. b/120241587

API / Behavior Changes

  • The artifact room-coroutines has been renamed to room-ktx following the same naming as other androidx artifacts.
  • beginTransaction , setTransactionSuccessful and endTransaction in RoomDatabase have been deprecated in favor of runInTransaction and the room-ktx extension function withTransaction .

Исправления ошибок

  • Fixed a bug where tokenizer arguments were being dropped if the tokenizer used was SIMPLE. b/125427014
  • Fixed a bug where Room would fail to correctly identify suspending functions with parameters whos type were an inner class. b/123767877
  • Fixed a bug where deferred @Query DAO method with INSERT , UPDATE or DELETE statements were eagerly preparing the query in the main thread. b/123695593
  • Fixed various bugs where Room would generate incorrect code for certain suspend functions. b/123466702 and b/123457323
  • Fixed a bug where deprecated usage of methods were not being correctly suppressed in generated code. b/117602586
  • Updated Room dependency of androidx.sqlite to 1.0.2 which contain fixes for correctly handling corrupted databases. b/124476912

Известные проблемы

  • Room 2.1.0-alpha05 depends on the kotlinx-metadata-jvm artifact which is not currently available in Maven Central ( KT-27991 ). This dependency can be resolved by adding maven { url "https://kotlin.bintray.com/kotlinx/" } to your project repositories.

Version 2.1.0-alpha04

25 января 2019 г.

Новые функции

  • DAO methods annotated with @Query containing INSERT , UPDATE or DELETE statements can now return async types Single , Mayble , Completable and ListenableFuture . Additionally they can also be suspend functions. b/120227284

API / Behavior Changes

  • Room will now throw an error if a non-abstract DAO method annotated with @Transaction returns an async type such as Single , Mayble , Completable , LiveData or ListenableFuture . Since transactions are thread confined it is currently impossible for Room to begin and end a transaction around a function that may peform queries in different threads. b/120109336
  • OnConflictStrategy.FAIL and OnConflictStrategy.ROLLBACK have been @Deprecated since they do not behave as intended with Android's current SQLite bindings. b/117266738

Исправления ошибок

  • Fixed a bug where Room wouldn't correctly use the TypeConverter of a return type if the DAO method was a suspend function. b/122988159
  • Fixed a bug where Room would incorrectly identify inherited suspend functions as non-suspending. b/122902595
  • Fixed a bug where Room would generate incorrect code when an @Embedded field was in a parent class and used in multiple child classes. b/121099048
  • Fixed an issue where the database would deadlock when invoking DAO suspend functions between a beginTransaction() and endTransaction() . b/120854786

Version 2.1.0-alpha03

4 декабря 2018 г.

Изменения API

  • The FTS tokenizer in @Fts3 / @Fts4 now takes a String instead of an Enum. This allows custom tokenizers to be used by Room. Built-in tokenizers are still defined in FtsOptions as string constants. b/119234881

Новые функции

  • Couroutines : DAO methods can now be suspend functions. To support suspend functions in Room a new artifact has been released, room-coroutines . b/69474692
  • DAO methods annotated with @Insert , @Delete or @Update now support ListenableFuture as return type. b/119418331

Исправления ошибок

  • Fixed a bug where Room would incorrectly attempt to find a constructor with columns in the ignoredColumns property of @Entity . b/119830714
  • Fixed a bug where Room would not mark DAO method parameters as final in their generated implementation. b/118015483
  • Fixed a bug where Room processor would crash when reporting an error on a query with special symbols. b/119520136
  • Fixed a bug where Room would decline other various Collection implementations as arguments of an IN expression. b/119884035
  • Fixed a bug where LiveData returned from Room would get garbage collected when observed forever causing it to no longer emit new data. b/74477406
  • Updated RoomDatabase 's close lock to reduce lock contention. b/117900450

Version 2.1.0-alpha02

30 октября 2018 г.

Новые функции

  • Added support for referencing a @DatabaseView in a @Relation . b/117680932

Исправления ошибок

  • Fixed a bug where Room would perform disk I/O in the main thread when subscribing and disposing from an Rx return type. b/117201279
  • Fixed a bug where Room would fail to find an appropriate type converter for a field in a Kotlin entity class. b/111404868
  • Fixed a bug where Room would generate incorrect code for a DAO interface implementation containing a Kotlin default method that has no arguments. b/117527454
  • Updated Room SQLite grammar parser, fixing a performance issue that would cause long build times. b/117401230

Version 2.1.0-alpha01

8 октября 2018 г.

Новые функции

  • FTS : Room now supports entities with a mapping FTS3 or FTS4 table. Classes annotated with @Entity can now be additionally annotated with @Fts3 or @Fts4 to declare a class with a mapping full-text search table. FTS options for further customization are available via the annotation's methods. b/62356416
  • Views : Room now supports declaring a class as a stored query, also known as a view using the @DatabaseView annotation. b/67033276
  • Auto Value : Room now supports declaring AutoValue annotated classes as entities and POJOs. The Room annotations @PrimaryKey , @ColumnInfo , @Embedded and @Relation can now be declared in an auto value annotated class' abstract methods. Note that these annotation must also be accompanied by @CopyAnnotations for Room to properly understand them. b/62408420
  • Additional Rx Return Types Support : DAO methods annotated with @Insert , @Delete or @Update now support Rx return types Completable , Single<T> and Maybe<T> . b/63317956
  • Immutable Types with @Relation : Room previously required @Relation annotated fields to be settable but now they can be constructor parameters.
  • enableMultiInstanceInvalidation : Is a new API in RoomDatabase.Builder to enable invalidation across multiple instances of RoomDatabase using the same database file. This multi-instance invalidation mechanism also works across multiple processes. b/62334005
  • fallbackToDestructiveMigrationOnDowngrade : Is a new API in RoomDatabase.Builder to automatically re-create the database if a downgrade happens. b/110416954
  • ignoredColumns : Is a new API in the @Entity annotation that can be used to list ignored fields by name. Useful for ignoring inherited fields on an entity. b/63522075

API / Behavior Changes

  • mCallback and mDatabase in RoomDatabase are now @Deprecated and will be removed in the next major version of Room. b/76109329

Исправления ошибок

  • Fixed two issues where Room wouldn't properly recover from a corrupted database or a bad migration during initialization. b/111504749 and b/111519144
  • Room will now properly use Kotlin's primary constructor in data classes avoiding the need to declare the fields as vars . b/105769985

Версия 2.0.0

Версия 2.0.0

1 октября 2018 г.

androidx.room 2.0.0 is released with no changes from 2.0.0-rc01.

Version 2.0.0-rc01

20 сентября 2018 г.

androidx.room 2.0.0-rc01 is released with no changes from 2.0.0-beta01.

Version 2.0.0-beta01

2 июля 2018 г.

API / Behavior Changes

  • Added RoomDatabase.Builder.setQueryExecutor() to allow customization of where queries are run
  • Added RxJava2 Observable support
  • Generated DAO and Database implementations are now final

Исправления ошибок

  • Specify class/field name in "cannot find getter for field" error b/73334503
  • Fixed RoomOpenHelper backwards compatibility with older versions of Room b/110197391

Pre-AndroidX Dependencies

For the pre-AndroidX versions of Room, include these dependencies:

dependencies {
    def room_version = "1.1.1"

    implementation "android.arch.persistence.room:runtime:$room_version"
    annotationProcessor "android.arch.persistence.room:compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor

    // optional - RxJava support for Room
    implementation "android.arch.persistence.room:rxjava2:$room_version"

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation "android.arch.persistence.room:guava:$room_version"

    // Test helpers
    testImplementation "android.arch.persistence.room:testing:$room_version"
}

Версия 1.1.1

Версия 1.1.1

19 июня 2018 г.

Room 1.1.1 is identical to Room 1.1.1-rc1 .

Version 1.1.1-rc1

May 16, 2018 We highly recommend using Room 1.1.1-rc1 instead of 1.1.0 if you are using migrations.

Fixed a bug where Room would not handle post migration initialization properly b/79362399

Версия 1.1.0

Version 1.1.0-beta3

19 апреля 2018 г.

Исправления ошибок

  • Fix compilation error when a Kotlin POJO references a relation entity that was defined in Java b/78199923

Version 1.1.0-beta2

5 апреля 2018 г.

Исправления ошибок

  • Fixed a critical bug in Room Rx Single and Maybe implementations where it would recycle the query ahead of time, causing problems if you add more than 1 observer to the returned Single or Maybe instances. b/76031240

  • [RoomDatabase.clearAllTables][ref-clearAllTables] will not VACUUM the database if it is called inside a transaction. b/77235565

Version 1.1.0-beta1

21 марта 2018 г.

Изменения API

  • Based on API Review feedback, @RawQuery does not accept passing a String as the query parameter anymore. You need to use [SupportSQLiteQuery][ref-SupportSQLiteQuery]. (see [SimpleSQLiteQuery][ref-SimpleSQLiteQuery] to easily create an instance of [SupportSQLiteQuery][ref-SupportSQLiteQuery] with argument support).
  • RoomDatabase.Builder's [fallbackToDestructiveMigrationFrom][ref-fallbackToDestructiveMigrationFrom] method now accepts vararg int instead of vararg Integer .

Исправления ошибок

  • [RoomDatabase.clearAllTables][ref-clearAllTables] now tries to return space back to the operating system by setting a WAL checkpoint and VACUUM ing the database.
  • [ @RawQuery ][ref-RawQuery] now accepts any Pojo for the observedEntities property as long as the Pojo references to one or more entities via its Embedded fields or Relation s. b/74041772
  • Paging: Room's DataSource implementation now correctly handles multi-table dependencies (such as relations, and joins). Previously these would fail to trigger new results, or could fail to compile. b/74128314

Version 1.1.0-alpha1

22 января 2018 г.

Новые функции

  • RawQuery : This new API allows @Dao methods to receive the SQL as a query parameter b/62103290 , b/71458963
  • fallBackToDestructiveMigrationsFrom : This new API in RoomDatabase.Builder allows for finer grained control over from which starting schema versions destructive migrations are allowed (as compared to fallbackToDestructiveMigration) b/64989640
  • Room now only supports newer Paging APIs (alpha-4+), dropping support for the deprecated LivePagedListProvider . To use the new Room alpha, you'll need to use paging alpha-4 or higher, and switch from LivePagedListProvider to LivePagedListBuilder if you haven't already.

Исправления ошибок

  • Improved support for Kotlin Kapt types. b/69164099
  • Order of fields do not invalidate schema anymore. b/64290754