1.gradle添加引用

 def room_version = "2.2.5"implementation "androidx.room:room-runtime:$room_version"annotationProcessor "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor

2.配置编译器选项

android {    ...    defaultConfig {        ...        javaCompileOptions {            annotationProcessorOptions {                arguments = [                    "room.schemaLocation":"$projectDir/schemas".toString(),  //配置并启用架构导出到给定目录中【"$projectDir/schemas".toString()】的json文件功能                    "room.incremental":"true",  //启用 Gradle 增量注释处理器                     "room.expandProjection":"true"] //配置 Room 以重写查询 ,设置成false则不需要导出到指定目录json文件            }        }    }}

不配置会报如下错误: 警告: 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.

3.添加权限

room数据库需要存储读写权限

      

4.创建实体类

需要在类上加上Entity注解

@Entity(tableName = "user",ignoredColumns = {"testField1"})  //实体类创建需要加上@Entity注解public class User {    @PrimaryKey(autoGenerate = true) //@PrimaryKey 声明id这个字段为主键。autoGenerate自增    public int id;    @ColumnInfo(name = "user_name")//@ColumnInfo将此列名重命名为name属性所赋值的名字    public String userName;    @ColumnInfo(name = "user_age")    public int userAge;    @ColumnInfo(name = "user_mobile")    public String userMobile;​    public String testField1;    @Ignore                       //@Ignore 此属性不在数据库生产列    public String testField2;​    public User() {    }​    @Ignore  //@Ignore 有参构造方法必须加上,否则将会报错    public User(String userName, int userAge) {        this.userName = userName;        this.userAge = userAge;    }    @Ignore  //@Ignore 有参构造方法必须加上,否则将会报错    public User(String userName, int userAge, String userMobile) {        this.userName = userName;        this.userAge = userAge;        this.userMobile = userMobile;    }​   }
 

5.看看Entity注解的内容

@Target(ElementType.TYPE) //定义作用域,ElementType.TYPE表示此注解可以作用在类、接口、注解和枚举上@Retention(RetentionPolicy.CLASS)//保留级别 RetentionPolicy.CLASS 保留到编译期间,反射可用public @interface Entity {    /**     * The table name in the SQLite database. If not set, defaults to the class name.     *  表名,不设置此属性的话会默认将className作为表名     * @return The SQLite tableName of the Entity.     */    String tableName() default "";​    /**     * List of indices on the table.     * 表索引  默认为空数组     * @return The list of indices on the table.     */    Index[] indices() default {};​    /**     * 是否从父类继承索引,如果是true,将会从其父类继承父类所声明的所有索引,即使父类此属性设置为false,只要本类设置为true,都会将父类中声明的索引全部继承过来。如果从父类继承了索引,那么从父类继承的索引将会根据Sqlite命名规则重新命名,因为Sqlite同一个数据库中不允许有相同的索引     *     默认为false     */    boolean inheritSuperIndices() default false;​    /**     * The list of Primary Key column names.     主键定义     * 

    * If you would like to define an auto generated primary key, you can use {@link PrimaryKey}     * annotation on the field with {@link PrimaryKey#autoGenerate()} set to {@code true}.     *     * @return The primary key of this Entity. Can be empty if the class has a field annotated     * with {@link PrimaryKey}.     */   String[] primaryKeys() default {};​   /**     * List of {@link ForeignKey} constraints on this entity.     *外键     * @return The list of {@link ForeignKey} constraints on this entity.     */   ForeignKey[] foreignKeys() default {};​   /**     * The list of column names that should be ignored by Room.     *

忽略的属性,即不在数据表中生成列的字段     * Normally, you can use {@link Ignore}, but this is useful for ignoring fields inherited from     * parents.     *

    * Columns that are part of an {@link Embedded} field can not be individually ignored. To ignore     * columns from an inherited {@link Embedded} field, use the name of the field.     *     * @return The list of field names.     */   String[] ignoredColumns() default {};}

6.创建接口Dao

@Dao //加上@Dao注解public interface UserDao {/***数据库操作注解分别有: Query  Insert  Update  Delete**/    //Query的值即使要执行的sql语句    @Query("SELECT * FROM user")    List getAll();​    @Query("SELECT * FROM user WHERE user_name in (:names)")    List getUsersByMames(List names);​    //注意点: 在Room使用中,模糊匹配的格式为" like '%' || :userName || '%' ",即在要匹配的参数值前后要加上 “||”,并且“%”要区分出来    @Query("SELECT * FROM user WHERE user_name like '%'|| :userName ||'%' LIMIT 1")    User getUserInfoByName(String userName);​    @Insert  //Insert 可以单独插入,也可以批量插入    void insertUser(User user);​    @Insert    void insertUsers(List users);}

7.创建DataBase抽象类

//创建database类继承自RoomDatabase类,必须声明成abstract//entities,指定需要创建的数据表的类,必须有Entity注解,version ,指定数据库版本@Database(entities = {User.class}, version = 1) public abstract class AppDataBase extends RoomDatabase {        public abstract UserDao userDao();​    private final static String DATABASE_NAME = "test_db";​    private static AppDataBase instance;​    public static AppDataBase getInstance(Context context) {        if (instance == null) {            synchronized (AppDataBase.class) {                if (instance == null) {                    instance = Room.databaseBuilder(context.getApplicationContext(), AppDataBase.class, DATABASE_NAME).build();                }            }        }        return instance;    }​}

8.使用

 private void createTestData() {        new Thread() {        //数据库操作不能再主线程,否则会报错            @Override            public void run() {                super.run();                User user = new User();                user.userAge = 18;                user.userName = "Databinding";                user.userMobile = "15888888888";​            //通过query语句删除单个数据                                               AppDataBase.getInstance(MainActivity.this).userDao().delete(user.userName);                //插入单条数据                AppDataBase.getInstance(MainActivity.this).userDao().insertUser(user);​                String names[] = new String[]{"Lifecycles", "LiveData", "Navigation", "Paging", "ViewModel"};                int[] ages = new int[]{19, 19, 18, 20, 21};                List userList = new ArrayList<>();                for (int i = 0; i < names.length; i++) {                    User mUser = new User(names[i], ages[i % ages.length]);                    userList.add(mUser);                }                //模拟删除数据                AppDataBase.getInstance(MainActivity.this).userDao().deletes(names);            //模拟批量插入    AppDataBase.getInstance(MainActivity.this).userDao().insertUsers(userList);​            }        }.start();    }

9.下一篇预告

下一篇将会对room数据库的升级以及复杂数据类型存储进行记录

更多相关文章

  1. Android第九讲——网络(六)xUtils
  2. android launch 初探
  3. android通讯录实例(二)
  4. Listview 中加上checbox 焦点问题
  5. Android开发小技巧:怎样在 textview 前面加上一个小图标。
  6. Error:Could not find com.android.tools.build:gradle:2.3.3. S
  7. android霓虹灯源代码——基础编
  8. android Fragment
  9. android获取imei和imsi

随机推荐

  1. Android消息提示框和对话框的使用
  2. android盒子的usb和串口之间的通信
  3. 自定义android用户控件,使用回调函数实现
  4. android sqlite遇到的一个吐血的问题
  5. Android退出应用的方法总结
  6. Android开发之核心特性SearchView的开发
  7. android linux(centos6) gradle环境配置
  8. 正确认识android内存管理原理
  9. android studio的安装与环境配置
  10. [置顶] Android-x86入门之--让你的Androi