Room数据库使用

请参考官方示例https://developer.android.google.cn/codelabs/basic-android-kotlin-training-intro-room-flow?hl=zh_cn#0
导入依赖

def roomVersion = "2.3.0"
implementation("androidx.room:room-runtime:$roomVersion")
annotationProcessor("androidx.room:room-compiler:$roomVersion")

实体类

@Entity(tableName = "user" )//tableName设置表名
public class User {
    //主键       自增
    @PrimaryKey(autoGenerate = true)
    private int uid;
    //唯一性
    @ColumnInfo(index = true)
    private String name;
    //属性名称改为 "pass_word"
    @ColumnInfo(name = "pass_word")
    @NonNull
    private String passWord;

    private String tag;

    @ColumnInfo(name = "is_online")
    private Boolean isOnline;


    public User() {
    }
    //不加忽略注解会出现 There are multiple good constructors and Room will ... 问题
    @Ignore
    public User(String name, String passWord, String tag) {
        this.name = name;
        this.passWord = passWord;
        this.tag = tag;
        this.isOnline = false;
    }


    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }
......
}

Dao

@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 name LIKE :name AND " + "pass_word LIKE :passWord LIMIT 1")
    User findByName(String name, String passWord);

    @Query("SELECT * FROM user WHERE is_online LIKE :online LIMIT 1")
    User findByOnline(Boolean online);

    //
    @Update
    void updateUser(User user);
    
    ////OnConflictStrategy.REPLACE:取代旧数据同时继续事务。
    //OnConflictStrategy.ROLLBACK:回滚事务。@Deprecated
    //OnConflictStrategy.ABORT:终止事务。
    //OnConflictStrategy.FAIL:事务失败。@Deprecated
    //OnConflictStrategy.IGNORE:忽略冲突。
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    //可以返回long别返回int会出现 Not sure how to handle insert method's return type问题
    long insert(User users);

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    void insert(User... users);

    //
    @Delete
    void delete(User user);

    @Query("DELETE  FROM user where name=:name")
    void delete(String name);
}

AppDatabase 

//Room数据库不能在主线程中进行操作,需要新开子线程
//如果出现 Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide room.schemaLocation annotation processor argument OR set exportSchema to false.
//在build gradle中添加(推荐)
//
//    android {
//        ...
//        defaultConfig {
//            ...
//            javaCompileOptions {
//                annotationProcessorOptions {
//                    arguments = ["room.schemaLocation":
//                                 "$projectDir/schemas".toString()]
//                }
//            }
//        }
//    }

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}

使用

AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "database-name").build();
db.userDao().insert(new User());

 Cannot find implementation for xxxDatabase. xxx_Impl does not exist...
 xxxDatabase_Impl does not exist at androidx.room.Room.getGeneratedImplementation....

annotationProcessor 是在使用 Java 注解处理器时的传统配置方法。它适用于使用 Java 编写的注解处理器。
kapt 是 Kotlin 编程语言特有的注解处理器配置方法。它利用了 Kotlin 编译器的一些特性,以更高效的方式处理注解。
请根据你的语言自行使用
Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
Room数据库不能在主线程中进行操作

posted @ 2021-11-22 17:27  勤奋的小铁  阅读(634)  评论(0编辑  收藏  举报