1,引入依赖
dependencies { implementation("androidx.room:room-runtime:2.4.2") annotationProcessor("androidx.room:room-compiler:2.4.2") }
2,标记实体类
import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "banner") data class Banner( val desc: String, @PrimaryKey val id: Int, val imagePath: String, val isVisible: Int, val order: Int, val title: String, val type: Int, val url: String )
3,对应的Dao类
import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update @Dao interface BannerDao { @get:Query("SELECT * FROM banner") val getBanners: List<Banner> @Query("SELECT * FROM banner WHERE 'id' = :userId") fun getBannerById(userId: Int): Banner? @Query("SELECT * FROM banner WHERE 'id' IN (:userIds)") fun getBannersByIds(userIds: IntArray): List<Banner> @Insert(onConflict = OnConflictStrategy.REPLACE) //重复时则会替换。 fun insert(vararg user: Banner) @Delete fun delete(vararg user: Banner) @Update fun update(vararg user: Banner) @Query("DELETE FROM banner") fun deleteAll() @Query("SELECT COUNT(*) FROM banner") fun countAll():Int }
4,RoomDatabase类
import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [Banner::class], version = 1,exportSchema = false) abstract class MyDatabase:RoomDatabase() { abstract fun bannerDao():BannerDao }
5,工具类
import android.content.Context import androidx.room.Room class DatabaseUtil private constructor(context: Context) { //双重检测单例 companion object { @Volatile private var databaseUtil: DatabaseUtil? = null fun getInstance(context: Context): DatabaseUtil { if (databaseUtil == null) { synchronized(DatabaseUtil::class) { if (databaseUtil == null) { databaseUtil = DatabaseUtil(context) } } } return databaseUtil!! } } val myDatabase: MyDatabase init { myDatabase = Room.databaseBuilder(context, MyDatabase::class.java, "my_database") .allowMainThreadQueries().build() } }