当前位置:   article > 正文

Android jetpack Room数据库(一)基本使用_配置并启用将数据库架构导出到给定目录中的

配置并启用将数据库架构导出到给定目录中的

1.gradle添加引用

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

2.配置编译器选项

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

不配置会报如下错误: 警告: 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数据库需要存储读写权限

  1. <!-- 读写 外部存储 权限 -->
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  3. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

4.创建实体类

需要在类上加上Entity注解

  1. @Entity(tableName = "user",ignoredColumns = {"testField1"}) //实体类创建需要加上@Entity注解
  2. public class User {
  3.   @PrimaryKey(autoGenerate = true) //@PrimaryKey 声明id这个字段为主键。autoGenerate自增
  4.   public int id;
  5.   @ColumnInfo(name = "user_name")//@ColumnInfo将此列名重命名为name属性所赋值的名字
  6.   public String userName;
  7.   @ColumnInfo(name = "user_age")
  8.   public int userAge;
  9.   @ColumnInfo(name = "user_mobile")
  10.   public String userMobile;
  11.   public String testField1;
  12.   @Ignore                       //@Ignore 此属性不在数据库生产列
  13.   public String testField2;
  14.   public User() {
  15.   }
  16.   @Ignore //@Ignore 有参构造方法必须加上,否则将会报错
  17.   public User(String userName, int userAge) {
  18.       this.userName = userName;
  19.       this.userAge = userAge;
  20.   }
  21.   @Ignore //@Ignore 有参构造方法必须加上,否则将会报错
  22.   public User(String userName, int userAge, String userMobile) {
  23.       this.userName = userName;
  24.       this.userAge = userAge;
  25.       this.userMobile = userMobile;
  26.   }
  27.  
  28. }
 

5.看看Entity注解的内容

  1. @Target(ElementType.TYPE) //定义作用域,ElementType.TYPE表示此注解可以作用在类、接口、注解和枚举上
  2. @Retention(RetentionPolicy.CLASS)//保留级别 RetentionPolicy.CLASS 保留到编译期间,反射可用
  3. public @interface Entity {
  4.   /**
  5.     * The table name in the SQLite database. If not set, defaults to the class name.
  6.     * 表名,不设置此属性的话会默认将className作为表名
  7.     * @return The SQLite tableName of the Entity.
  8.     */
  9.   String tableName() default "";
  10.   /**
  11.     * List of indices on the table.
  12.     * 表索引 默认为空数组
  13.     * @return The list of indices on the table.
  14.     */
  15.   Index[] indices() default {};
  16.   /**
  17.     * 是否从父类继承索引,如果是true,将会从其父类继承父类所声明的所有索引,即使父类此属性设置为false,只要本类设置为true,都会将父类中声明的索引全部继承过来。如果从父类继承了索引,那么从父类继承的索引将会根据Sqlite命名规则重新命名,因为Sqlite同一个数据库中不允许有相同的索引
  18.     *
  19.     默认为false
  20.     */
  21.   boolean inheritSuperIndices() default false;
  22.   /**
  23.     * The list of Primary Key column names.
  24.     主键定义
  25.     * <p>
  26.     * If you would like to define an auto generated primary key, you can use {@link PrimaryKey}
  27.     * annotation on the field with {@link PrimaryKey#autoGenerate()} set to {@code true}.
  28.     *
  29.     * @return The primary key of this Entity. Can be empty if the class has a field annotated
  30.     * with {@link PrimaryKey}.
  31.     */
  32.   String[] primaryKeys() default {};
  33.   /**
  34.     * List of {@link ForeignKey} constraints on this entity.
  35.     *外键
  36.     * @return The list of {@link ForeignKey} constraints on this entity.
  37.     */
  38.   ForeignKey[] foreignKeys() default {};
  39.   /**
  40.     * The list of column names that should be ignored by Room.
  41.     * <p> 忽略的属性,即不在数据表中生成列的字段
  42.     * Normally, you can use {@link Ignore}, but this is useful for ignoring fields inherited from
  43.     * parents.
  44.     * <p>
  45.     * Columns that are part of an {@link Embedded} field can not be individually ignored. To ignore
  46.     * columns from an inherited {@link Embedded} field, use the name of the field.
  47.     *
  48.     * @return The list of field names.
  49.     */
  50.   String[] ignoredColumns() default {};
  51. }

6.创建接口Dao

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

7.创建DataBase抽象类

  1. //创建database类继承自RoomDatabase类,必须声明成abstract
  2. //entities,指定需要创建的数据表的类,必须有Entity注解,version ,指定数据库版本
  3. @Database(entities = {User.class}, version = 1)
  4. public abstract class AppDataBase extends RoomDatabase {
  5.    
  6.   public abstract UserDao userDao();
  7.   private final static String DATABASE_NAME = "test_db";
  8.   private static AppDataBase instance;
  9.   public static AppDataBase getInstance(Context context) {
  10.       if (instance == null) {
  11.           synchronized (AppDataBase.class) {
  12.               if (instance == null) {
  13.                   instance = Room.databaseBuilder(context.getApplicationContext(), AppDataBase.class, DATABASE_NAME).build();
  14.               }
  15.           }
  16.       }
  17.       return instance;
  18.   }
  19. }

8.使用

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

9.下一篇预告

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

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/807506?site
推荐阅读
相关标签
  

闽ICP备14008679号