当前位置:网站首页>Room first use

Room first use

2022-06-11 00:29:00 Liuyichu

brief introduction :
Room The persistence library is in SQLite An abstraction layer is provided on , In order to make full use of SQLite At the same time , Be able to access the database smoothly . say concretely ,Room It has the following advantages :

  • in the light of SQL Compile time validation of queries .
  • Convenient annotations that minimize duplication and error prone boilerplate code .
  • Simplified database migration path .

Room Contains three main components :

  • The database class , It is used to save the database and serve as the main access point for the underlying connection of application persistence data .
  • Data entity , Used to represent tables in the database of the application .
  • Data access object (DAO), Provide your application to query 、 to update 、 Methods of inserting and deleting data in the database .

1. Create entities

One night's sleep is defined as an annotated data class representing database entities , Need record
The start time of a night's sleep 、
The end of a night's sleep 、
The quality score of one night's sleep 、
Besides , I need one more ID To uniquely identify that night .

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "daily_sleep_quality_table")
data class SleepNight(
       @PrimaryKey(autoGenerate = true)
       var nightId: Long = 0L,

       @ColumnInfo(name = "start_time_milli")
       val startTimeMilli: Long = System.currentTimeMillis(),

       @ColumnInfo(name = "end_time_milli")
       var endTimeMilli: Long = startTimeMilli,

       @ColumnInfo(name = "quality_rating")
       var sleepQuality: Int = -1
)

establish SleepNight Data class , Parameters include ID、 Starting time 、 End time , And a digital sleep quality score .

explain :

 You must initialize  sleepQuality, So set it to  -1, To indicate that no quality data has been collected .
 Initialize the start time to a known valid time . It is recommended to select the current time in milliseconds .
 You must also initialize the end time . Set it to start time , This means that no end time has been recorded .

1. take nightId Identify as primary key , Please for nightId Attribute addition @PrimaryKey annotation . The parameter autoGenerate Set to true, Give Way Room Generate... For each entity ID. This will ensure that every night ID It must be unique .

2. Above the class declaration , Add... To the data class @Entity annotation . This annotation has several possible parameters . By default (@Entity No parameters ), The table name is the same as the class name . however , We're going to use daily_sleep_quality_table This useful table name .tableName Is an optional parameter , But it is strongly recommended to use .

3. Add... For the remaining attributes @ColumnInfo annotation . As shown below , Use parameters to customize attribute names .

2. establish DAO

Define a data access object (DAO), Can be DAO Consider defining a custom interface for accessing the database ,DAO Provides insertion of 、 A convenient way to delete and update databases .

Use Room Database time , You need to define and call... In your code Kotlin Function to query the database . these Kotlin The function maps to SQL Inquire about . You can use annotations in DAO Define these mappings in , and Room Will create the necessary code .

For common database operations ,Room The library provides convenient annotations , for example @Insert、@Delete and @Update.

For all other operations , All use @Query annotation . You can write SQLite Any queries supported .

Another benefit is , When you are in Android Studio When creating a query in , The compiler will check your SQL Query for syntax errors .

For the sleep tracker database for sleep nights , Must be able to perform the following :

  • Insert new night .
  • Update the end time and quality score of existing nights .
  • Get the data of a specific night according to the key .
  • Get all night data , And display .
  • Get the last night's data .
  • Delete all entries in the database .
@Dao
interface SleepDatabaseDao {
    @Insert
    fun insert(night: SleepNight)
    
    @Update
    fun update(night: SleepNight)
    
    @Query("SELECT * from daily_sleep_quality_table WHERE nightId = :key")
    fun get(key: Long): SleepNight?
    
    @Query("DELETE FROM daily_sleep_quality_table")
    fun clear()
    
    @Query("SELECT * FROM daily_sleep_quality_table ORDER BY nightId DESC LIMIT 1")
    fun getTonight(): SleepNight?
    
    @Query("SELECT * FROM daily_sleep_quality_table ORDER BY nightId DESC")
    fun getAllNights(): LiveData<List<SleepNight>>
}

explain :
1. all DAO You need to use @Dao Keyword for annotation .
2. Insert new night : @Insert annotation . stay @Insert Next , Add one insert() function , This function will SleepNight As its parameter . Be accomplished .Room Insert the build into the database SleepNight All the code required . When you come from Kotlin Code calls insert() when ,Room Will perform SQL Query to insert the entity into the database .( Be careful : You can call this function at will .)
3. Update existing night : add to @Update Annotate as well as put a SleepNight parametric update() function . The updated entity is an entity with the same key as the incoming entity . You can update some or all of the other attributes of the entity .
4. There are no easy-to-use annotations for other functions , So you have to use @Query Annotate and provide SQLite Inquire about .
5. Get the data of a specific night according to the key : Add one @Query Notes and a get() function ; This function accepts Long key Parameters , And the return can be null Of SleepNight. take String Parameters added to @Query( This is a SQLite Inquire about ), Used to retrieve specific SleepNight All columns in the entry .

  • choice daily_sleep_quality_table All columns in
  • WHERE Statement nightId matching :key Parameters .

Please note that :key. The English colon is used in the query to refer to the parameters in the function .

6. Delete all entries in the database : Add another @Query, And for from daily_sleep_quality_table Delete in Of all information clear() Functions and SQLite Inquire about . This query does not delete the table itself .

@Delete Annotations delete an item , You can use @Delete And provide a list of nights to delete . The disadvantage of this method is , You need to extract or understand the contents of the table [email protected] Annotations are ideal for deleting specific entries , But it is inefficient in clearing all entries in the table .
7. Get the last night's data : add to @Query Annotations and a getTonight() function . send getTonight() Back to SleepNight for null, So that the function can handle the case that the table is empty .( The table is empty at the beginning , It is also empty after the data is cleared .)
To get... From the database “ Tonight? ” The data of , You can write a SQLite Inquire about , For returning to press nightId The first element in the result list in descending order . Use LIMIT 1 Only one element can be returned .

8. Get all night data : add to @Query Annotations and a getAllNights() function :
Give Way SQLite Query returns daily_sleep_quality_table All columns in , And sort them in descending order .
Give Way getAllNights() return SleepNight A list of entities as LiveData.Room Will keep this up to date for you LiveData, in other words , You only need to get the data explicitly once .

3. Create and test ROOM database

@Database(entities = [SleepNight::class], version = 1, exportSchema = false)
abstract class SleepDatabase : RoomDatabase() {

	//  For each... Associated with the database  DAO  class , The database class must define an abstract method with zero parameters , And back to  DAO  Class .
   abstact fun getDao():SleepDatabaseDao
 
   companion object {

       @Volatile
       private var INSTANCE: SleepDatabase? = null

       fun getInstance(context: Context): SleepDatabase {
           synchronized(this) {
               var instance = INSTANCE

               if (instance == null) {
                   instance = Room.databaseBuilder(
                           context.applicationContext,
                           SleepDatabase::class.java,
                           "sleep_history_database"
                   )
                           .fallbackToDestructiveMigration()
                           .build()
                   INSTANCE = instance
               }
               return instance
           }
       }
   }
}
原网站

版权声明
本文为[Liuyichu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206102307355148.html