Room是Google Jetpack家族的一员,Room在SQLite上提供了一个抽象层,以便在充分利用SQLite的强大功能的同时,能够流畅地访问数据库。使用起来也比较方便;
它有如下优势:
1 针对 SQL 查询的编译时验证。
2 可最大限度减少重复和容易出错的样板代码的方便注解。
3 简化了数据库迁移路径
基本组件
Database: 访问底层数据库的入口,数据库持有者;
Entity: 代表数据库中的表(table),一般用注解;
Data Access Object (DAO): 数据库访问者,其中定义了数据库的增删改查 函数 ;
栗子:
def room_version = "2.2.5"
api "androidx.room:room-runtime:$room_version"
testImplementation "androidx.room:room-testing:$room_version"
annotationProcessor "android.arch.persistence.room:compiler:1.1.1"
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "User")
public class User {
@PrimaryKey(autoGenerate = true)
public int uid;
public String firstName;
public String lastName;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
import java.util.List;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
@Dao
public interface UserDao {
@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 firstName LIKE :firstName AND "+"lastName LIKE :lastName LIMIT 1")
User findByName(String firstName,String lastName);
@Insert
void insertAll(User... users);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(User user);
@Delete
void delete(User user);
@Query("update User set lastName = :lastName where firstName = :firstName")
void updateUserLastName(String firstName,String lastName);
}
import java.io.File;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
@Database(entities = {User.class},version = 1)
public abstract class AppDatabase extends RoomDatabase {
private volatile static AppDatabase dataBase;
public static Context mContext;
public static String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/User/";
public static final String DATABASE = path + "User.db";
public static void setContext(Context context) {
mContext = context;
}
public static AppDatabase getDataBase() {
synchronized (AppDatabase.class) {
File file = new File(path);
if (!file.isDirectory() || !file.exists()) {
file.mkdirs();
}
if (dataBase == null) {
dataBase =
Room.databaseBuilder(mContext, AppDatabase.class, DATABASE)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.fallbackToDestructiveMigrationOnDowngrade()
.setJournalMode(JournalMode.TRUNCATE)
.build();
}
}
return dataBase;
}
public static void resetDB() {
dataBase = null;
}
public abstract UserDao userDao();
}
onConflict设置当事务中遇到冲突时的策略:
onConflict设置当事务中遇到冲突时的策略
OnConflictStrategy.REPLACE : 替换旧值,继续当前事务
OnConflictStrategy.ROLLBACK : 回滚当前事务
OnConflictStrategy.ABORT : 结束当前事务、回滚
OnConflictStrategy.FAIL : 当前事务失败、回滚
OnConflictStrategy.NONE : 忽略冲突,继续当前事务