room为Jetpack的数据库组件,是sqlite的封装,可以更加方便操作数据库。而且支持RxJava和LiveData
先配置下root下面的build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
maven { url "https://jitpack.io" }
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.2'
classpath 'androidx.navigation:navigation-safe-args-gradle-plugin:latest.release'
}
}
allprojects {
repositories {
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
maven { url "https://jitpack.io" }
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
添加依赖
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.tests"
minSdkVersion 19
targetSdkVersion 29
versionCode 1
versionName "1.0"
//数据库配置,添加这个配置是为了避免编译报错
javaCompileOptions {
annotationProcessorOptions {
arguments = [
"room.schemaLocation" : "$projectDir/schemas".toString(),
"room.incremental" : "true",
"room.expandProjection": "true"]
}
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:latest.release'
//其他组件
implementation 'androidx.legacy:legacy-support-v4:latest.release'
implementation 'androidx.annotation:annotation:latest.release'
//数据库
//kapt "androidx.room:room-compiler:latest.release"
//implementation "androidx.room:room-ktx:latest.release"
implementation "androidx.room:room-runtime:latest.release"
annotationProcessor "androidx.room:room-compiler:latest.release"
implementation "androidx.room:room-rxjava2:latest.release"
implementation "androidx.room:room-guava:latest.release"
//squareup
implementation 'io.reactivex.rxjava2:rxjava:latest.release'
implementation 'io.reactivex.rxjava2:rxandroid:latest.release'
}
}
先建立一个数据表,同时也是bean类
package com.example.tests.data.database;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity
public class User {
@PrimaryKey(autoGenerate = true)
public int uid;
@ColumnInfo(name = "name")
public String name;
@ColumnInfo(name = "pwd")
public String password;
}
写数据库接口方法
package com.example.tests.data.database;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
@Dao
public interface UserDao {
//此处的user, 是类的名字,类名即表名
@Query("SELECT * FROM user")
List<User> getAll();
@Query("SELECT * FROM user WHERE uid IN (:userIds)")
List<User> loadAllByIds(int[] userIds);
@Query("SELECT * FROM user WHERE name LIKE :first AND name LIKE :last LIMIT 1")
User findByName(String first, String last);
@Insert
void insertAll(User... users);
@Delete
void delete(User user);
}
定义接口方法的生成类
package com.example.tests.data.database;
import androidx.room.Database;
import androidx.room.RoomDatabase;
@Database(entities = {User.class}, version = 2)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
使用的时候,可以在Application中开启
//初始化数据库
AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "database-name")
.addMigrations(MIGRATION_1_2).build();
.addMigrations(MIGRATION_1_2)方法是升级数据库使用的
一般在改变表格结构才需要
//对数据库进行迁移。
Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("CREATE TABLE `user_t` (`uid` INTEGER PRIMARY KEY autoincrement ,`name` TEXT,`pwd` TEXT)");
database.execSQL("INSERT INTO `user_t` (`name` , `pwd`) SELECT `name`, `pwd` FROM `user`");
database.execSQL("DROP TABLE `user`");
database.execSQL("ALTER TABLE `user_t` RENAME TO `user`");
}
};
使用上很简单
User u = new User();
u.name = user.getDisplayName();
u.password = user.getPassword();
MainApplication.db.userDao().insertAll(u);