赞
踩
-
- 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
- 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.
room数据库需要存储读写权限
- <!-- 读写 外部存储 权限 -->
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
需要在类上加上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;
- }
-
-
- }

- @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.
- 主键定义
- * <p>
- * 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.
- * <p> 忽略的属性,即不在数据表中生成列的字段
- * Normally, you can use {@link Ignore}, but this is useful for ignoring fields inherited from
- * parents.
- * <p>
- * 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 {};
- }

- @Dao //加上@Dao注解
- public interface UserDao {
- /**
- *数据库操作注解分别有: Query Insert Update Delete
- *
- */
- //Query的值即使要执行的sql语句
- @Query("SELECT * FROM user")
- List<User> getAll();
-
- @Query("SELECT * FROM user WHERE user_name in (:names)")
- List<User> getUsersByMames(List<String> 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<User> users);
- }

- //创建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;
- }
-
- }

- 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<User> 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();
- }

下一篇将会对room数据库的升级以及复杂数据类型存储进行记录
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。