- Урок 7. Room. Insert, Update, Delete, Transaction
- Insert
- Вставка нескольких объектов
- Получение id
- Режимы вставки
- Update
- Delete
- Транзакции
- Classes
- Annotation Types
- Gradle dependencies
- Androidx artifact mapping:
- Androidx class mapping:
- Overview
- Summary
- Fields
- Room Database Queries Using DAO
- Defining The Convenience Method
- Insert Query
- On Conflict Strategy
- ROLLBACK
- ABORT
- FAIL
- IGNORE
- REPLACE
- Update Query
- Delete Query
- Query for information in Room Database Queries Using DAO
- Parsing parameters into the query
- OnConflictStrategy
- Summary
- Constants
- Inherited methods
- Constants
- ABORT
- IGNORE
- REPLACE
- ROLLBACK
- Annotations
- Classes
- Enums
- Exceptions
- OnConflictStrategy
- Summary
- Constants
- Inherited methods
- Constants
- ABORT
- IGNORE
- REPLACE
- ROLLBACK
- Annotations
- Classes
- Enums
- Exceptions
Урок 7. Room. Insert, Update, Delete, Transaction
В этом уроке рассмотрим подробнее аннотации Insert, Update и Delete. А также узнаем, как использовать транзакции в Room.
Полный список уроков курса:
Insert
Аннотация Insert — это простой способ вставить объект в базу данных. Мы уже использовали ее в примерах прошлых уроков.
Использование этой аннотации выглядит так:
В Dao интерфейсе описываем метод, который на вход принимает Entity объект. К методу добавляем аннотацию Insert и Room сгенерирует необходимый код в реализации этого интерфейса.
Давайте посмотрим, какие еще возможности у нас есть.
Вставка нескольких объектов
Мы можем передавать в метод не один, а несколько объектов, используя varargs
Также, это может быть список:
Или это вообще может быть любой Iterable:
При вызове этого метода вы можете использовать массив или коллекцию.
Получение id
При вставке метод Insert может возвращать id только что добавленной записи. Для этого надо описать метод так, чтобы он возвращал long.
Если в Employee есть числовой первичный ключ, то именно его значение вы и получите.
В случае добавления нескольких записей, необходимо использовать long[]
Режимы вставки
Рассмотрим ситуацию, когда мы вставляем в таблицу запись, но обнаруживается, что запись с таким ключом там уже есть. По умолчанию мы получим ошибку: SQLiteConstraintException: UNIQUE constraint failed. И ничего в базу не запишется.
Но это можно поменять с помощью параметра onConflict.
В режиме REPLACE старая запись будет заменена новой. Этот режим хорошо подходит, если вам надо вставить запись, если ее еще нет в таблице или обновить запись, если она уже есть.
Также есть режим IGNORE. В этом режиме будет оставлена старая запись и операция вставки не будет выполнена.
Более подробно об этих режимах можно прочесть здесь.
Update
Эта аннотация аналогична Insert, но она не вставляет, а обновляет объекты в бд.
Так же, как и с Insert мы можем использовать коллекции и varargs, чтобы обновлять несколько объектов сразу.
Update ищет в бд запись по ключу. Если не найдет, то ничего не произойдет. Если найдет, то обновит все поля, а не только те, которые мы заполнили в Entity объекте.
Мы можем получить количество обновленных записей. Для этого опишите метод так, чтобы он возвращал int.
Как и Insert, Update поддерживает параметр onConflict.
Delete
Методы с аннотацией Delete будут удалять объекты.
В Delete методах мы также можем использовать коллекции и varargs, чтобы удалять несколько объектов сразу.
Delete ищет в бд запись по ключу.
Мы можем получить количество удаленных записей. Для этого необходимо описать метод так, чтобы он возвращал int.
Аннотации Insert, Update и Delete позволяют выполнить простые операции. Для более сложных действий необходимо использовать SQL запросы: INSERT, UPDATE и DELETE. Это можно сделать с помощью аннотации Query. В следующем уроке мы рассмотрим эту возможность.
Транзакции
Аннотация @Transaction позволяет выполнять несколько методов в рамках одной транзакции.
Рассмотрим пример, когда нам нужно добавить объекты Car и Employee:
EmployeeCarDao — отдельный Dao объект для работы с комбинацией Car и Employee. В нем описываем методы для вставки объектов по отдельности, а затем оба этих метода вызываем в одном методе с аннотацией Transaction. В итоге вставятся либо оба объекта, либо, в случае возникновения ошибки, ни один из них.
Обратите внимание, что в этом случае Dao — не интерфейс, а абстрактный класс.
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
Classes
Annotation Types
Gradle dependencies
compile group: ‘androidx.room’, name: ‘room-common’, version: ‘2.3.0-alpha03’
- groupId: androidx.room
- artifactId: room-common
- version: 2.3.0-alpha03
Artifact androidx.room:room-common:2.3.0-alpha03 it located at Google repository (https://maven.google.com/)
Androidx artifact mapping:
Androidx class mapping:
Overview
Set of conflict handling strategies for various Dao methods.
Summary
Fields | |
---|---|
public static final int | ABORT |
OnConflict strategy constant to abort the transaction.
OnConflict strategy constant to fail the transaction.
OnConflict strategy constant to ignore the conflict.
OnConflict strategy constant to replace the old data and continue the transaction.
OnConflict strategy constant to rollback the transaction.
Fields
OnConflict strategy constant to replace the old data and continue the transaction.
An Insert DAO method that returns the inserted rows ids will never return -1 since this strategy will always insert a row even if there is a conflict.
Deprecated: Does not work with Android’s current SQLite bindings. Use OnConflictStrategy.ABORT to roll back the transaction.
OnConflict strategy constant to rollback the transaction.
OnConflict strategy constant to abort the transaction. The transaction is rolled back.
Deprecated: Does not work as expected. The transaction is rolled back. Use OnConflictStrategy.ABORT.
OnConflict strategy constant to fail the transaction.
OnConflict strategy constant to ignore the conflict.
An Insert DAO method that returns the inserted rows ids will return -1 for rows that are not inserted since this strategy will ignore the row if there is a conflict.
Источник
Room Database Queries Using DAO
The first two articles, we have learned how to create Room database in android studio. Also, we quickly learned how to insert, update, delete and collect rows from it. If it is the first time to visit Android Hands website, you can use the below links to study Room Database from the first part. Furthermore, In this article we will learn in depth how use Room Database Queries in Android Studio Using DAO (Data Access Objects).
Many android applications that depend on local persistence requires different ways to filter users data. In this article we will learn in depth the different Room Database query types either convenience queries or Queries for information using Room Dao classes. Moreover, we will learn these queries on a real simple ToDo List App.
Defining The Convenience Method
In Room Database there are multiple convenience methods that we can use in in Dao. For example, Insert, delete and update methods.
Insert Query
The following example code shows the different ways to insert one and multiple rows using Insert Query.
Furthermore,The insert method can receive one or more parameters. If it received one parameter, it should return long value which is the id of the new inserted row. Moreover, If it received list of parameters, it should return long[] which considered the list of id`s of the insert rows.
On Conflict Strategy
From the above code, we note the the @Insert annotation take a parameter which is onConflict. Fore instance we have set the on conflict strategy as Replace. So, to understand the on conflict strategy, we need to know what is constraint violation. Sometimes we need to define specific columns and not null, unique or specify the data type as integer. After that when we try to do an update or insert queries that violates the constraint (different data type). By the default SQLite database abort the operation in the progress and returns a constraint violation error. SQLite also allows one to define alternative ways for dealing with constraint violations.
ROLLBACK
When a constraint violation occurs, an immediate ROLLBACK occurs, thus ending the current transaction, and the command aborts with a return code of SQLITE_CONSTRAINT. If no transaction is active then this algorithm works the same as ABORT.
ABORT
When a constraint violation occurs, the command backs out any prior changes it might have made and aborts with a return code of SQLITE_CONSTRAINT. This is the default behavior for SQLite.
FAIL
When a constraint violation occurs, the command aborts with a return code SQLITE_CONSTRAINT. But any changes to the database that the command made prior to encountering the constraint violation are preserved and are not backed out by FAIL strategy. For example, if an UPDATE statement encountered a constraint violation on the 100th row that it attempts to update, then the first 99 row changes are preserved but change to rows 100 and beyond never occur.
IGNORE
When a constraint violation occurs, the one row that contains the constraint violation is not inserted or changed. But the command continues executing normally. Other rows before and after the row that contained the constraint violation continue to be inserted or updated normally.So, when you use IGNORE strategy, no error is returned.
REPLACE
When a UNIQUE constraint violation occursand you are using a REPLACE strategy, the pre-existing row that caused the constraint violation is removed prior to inserting or updating the current row. Thus the insert or update always occurs. The command continues executing normally. No error is returned.
Update Query
Easily, we update a set of entities using a convenience update query. Just, cast the entity or list of entities in the query method. Furthermore it uses the query that matches the id of the entity.
Delete Query
The Delete convenience method removes a set of entities, given as parameters, from the database. It uses the primary keys to find the entities to delete.
Query for information in Room Database Queries Using DAO
Moreover, we can use Room Database Queries Using DAO. Just, by using @Query() annotation in Dao classes. It helps to perform insert,update,delete and select queries. Each method is verified at compile time so that we can detect the query errors( as wrong column names).
From the above example, we not that the collectItems() method returns a list of todo table. At run time Room database detects that it is select query for all fields in todo table.
Parsing parameters into the query
In most of our apps we need to perform filtering on Room database. such as we need to filter the completed task items. Moreover, we need to filter by date. Also, arrange and limit number of rows. So that Room database allow us to parse parameter into the query. See the following example.
The above query will collect entities that value of completed column like the caste value of bCompleted. Another example shows how to collect entities where date lies between two dates.
This article not covers all about Room Database Queries Using DAO, as we explain it in the next article where we ready to learn Room Relational Database.
Источник
OnConflictStrategy
public abstract @interface OnConflictStrategy
implements Annotation
android.arch.persistence.room.OnConflictStrategy |
Set of conflict handling strategies for various Dao methods.
Summary
Constants
OnConflict strategy constant to abort the transaction.
OnConflict strategy constant to fail the transaction.
OnConflict strategy constant to ignore the conflict.
OnConflict strategy constant to replace the old data and continue the transaction.
OnConflict strategy constant to rollback the transaction.
Inherited methods
From interface java.lang.annotation.Annotation
abstract Class | annotationType() |
abstract boolean | equals(Object arg0) |
abstract int | hashCode() |
abstract String | toString() |
Constants
ABORT
OnConflict strategy constant to abort the transaction.
Constant Value: 3 (0x00000003)
OnConflict strategy constant to fail the transaction.
Constant Value: 4 (0x00000004)
IGNORE
OnConflict strategy constant to ignore the conflict.
Constant Value: 5 (0x00000005)
REPLACE
OnConflict strategy constant to replace the old data and continue the transaction.
Constant Value: 1 (0x00000001)
ROLLBACK
OnConflict strategy constant to rollback the transaction.
Constant Value: 2 (0x00000002)
Annotations
Classes
Enums
Exceptions
Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.
Источник
OnConflictStrategy
public abstract @interface OnConflictStrategy
implements Annotation
android.arch.persistence.room.OnConflictStrategy |
Set of conflict handling strategies for various Dao methods.
Summary
Constants
OnConflict strategy constant to abort the transaction.
OnConflict strategy constant to fail the transaction.
OnConflict strategy constant to ignore the conflict.
OnConflict strategy constant to replace the old data and continue the transaction.
OnConflict strategy constant to rollback the transaction.
Inherited methods
From interface java.lang.annotation.Annotation
abstract Class | annotationType() |
abstract boolean | equals(Object arg0) |
abstract int | hashCode() |
abstract String | toString() |
Constants
ABORT
OnConflict strategy constant to abort the transaction.
Constant Value: 3 (0x00000003)
OnConflict strategy constant to fail the transaction.
Constant Value: 4 (0x00000004)
IGNORE
OnConflict strategy constant to ignore the conflict.
Constant Value: 5 (0x00000005)
REPLACE
OnConflict strategy constant to replace the old data and continue the transaction.
Constant Value: 1 (0x00000001)
ROLLBACK
OnConflict strategy constant to rollback the transaction.
Constant Value: 2 (0x00000002)
Annotations
Classes
Enums
Exceptions
Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.
Источник