Room的使用以及数据库的升级

开发前的准备工作

  1. 添加依赖
    implementation "android.arch.persistence.room:runtime:1.1.1"
    annotationProcessor "android.arch.persistence.room:compiler:1.1.1"

     

  2. schemas生成的路径设置
android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                //room的数据库概要、记录
                arguments = ["room.schemaLocation":
                                     "$projectDir/schemas".toString()]
            }
        }
    }
    sourceSets {
        //数据库概要、记录存放位置
        androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
    }
}

数据表的生成

  1. 实体类即数据表的生成
    
    @Entity(tableName = "users")//标注为数据表,默认为实体类的名称,也可以自定义表名
    //@Entity(primaryKeys = {"firstName", "lastName"})复合主键
    //@Entity(indices = {@Index("name"),@Index(value = {"last_name", "address"})})为列添加索引
    //@Entity(foreignKeys = @ForeignKey(entity = User.class,
    //                                  parentColumns = "id",
    //                                  childColumns = "user_id",
    //                                  onDelete = CASCADE))
    //为数据表添加外键
    
    
    //有时候,某个字段或者几个字段必须是唯一的。你可以通过把@Index注解的unique属性设置为true来实现
    //唯一性。下面的代码防止了一个表中的两行数据出现firstName和lastName字段的值相同的情况:
    //@Entity(indices = {@Index(value = {"first_name", "last_name"},
    //        unique = true)})
    
    
    
    public class User {
        @PrimaryKey(autoGenerate = true)//单个主键,自增长
        private int id;
    
        @ColumnInfo(name = "first_name")//定义列名
        private String firstName;
    
        @ColumnInfo(name = "last_name")
        private String lastName;
    
        @ColumnInfo(name = "book_id")
        private String bookId;
        
        @Ignore//用来标记不需要持久化的字段
        private Student std;
    
        @Embedded//用来处理model嵌套的情况,如Library 中包含 Address
        private Address add;
        //例如下面的代码,一个User对象的表就有了如下的字段::id,firstName,street,state,city, 以
        //及post_code。
        //class Address {
        //    public String street;
        //    public String state;
        //    @ColumnInfo(name = "city")
        //    public String city;
        //    @ColumnInfo(name = "post_code")
        //    public int postCode;
        //}
     
        //@Entity
        //class User {
        //    @PrimaryKey
        //    public int id;
        //    public String firstName;
        //    @Embedded
        //    public Address address;
        //}
    
    
    
    
        //@ForeignKey
        //为model添加外键,建立对象之间的所属关系,也可以通过@Relation来实现
        //添加onDelete = CASCADE可以在进行级联删除,简单讲就是,如果删除了某条library数据,那么与之            //关联的category数据和与category数据关联的book数据,都会被删除
    
    //toString和get,set方法请自行生成
    }

     

  2. dao的实现
    @Dao//标注为实体类查询数据库的方法
    public interface UserDao {
        @Query("SELECT * FROM user")
        List getAll();
    
        @Query("SELECT * FROM user WHERE id IN (:userIds)")
        List loadAllByIds(int[] userIds);
    
        @Query("SELECT * FROM user WHERE first_name LIKE :first AND "
                + "last_name LIKE :last LIMIT 1")
        User findByName(String first, String last);
    
        @Insert//被标注的方法只能返回 void,long,Long,long[],Long[]或者List
        void insertAll(User... users);
    
        @Delete//被标注的方法只能返回void,int
        void delete(User user);
    
        @Update//被标注的方法只能返回void,int
        void updata(User... users);
    
        @Query("SELECT first_name,last_name  FROM user")//获取指定的列,需要重新写一个实体,如下
        List getAllName();
    
    
        //public class AllName{
    
        //    @ColumnInfo(name = "first_name")
        //    public String firstName;
        //    @ColumnInfo(name = "last_name  ")
        //    public String lastName;
        //   }
    
        @Query("SELECT * FROM user")//需添加LiveData库
        LiveData> queryReturnLiveData();
    
        @Query("SELECT * FROM user")//需添加rxjava
        Flowable> queryReturnFlowable();
    
    
        //多表查询
        @Query("SELECT * FROM library "
                + "INNER JOIN category ON category.library_id = library.id "
                + "INNER JOIN book ON book.category_id = category.id "
                + "WHERE book.name LIKE :bookName")
        Library findLibraryByBookName(String bookName);
    }
    

     

  3. RoomDatabase的生成
    
    @Database(entities = User.class,version = 1)//数据库获取实体操作数据库的dao
    public abstract  class AppDatabase extends RoomDatabase {
        public abstract UserDao userDao();
    }

     

  4. 类型转化器

public class Converters {
    @TypeConverter
    public static Date fromTimestamp(Long value) {
        return value == null ? null : new Date(value);
    }
 
    @TypeConverter
    public static Long dateToTimestamp(Date date) {
        return date == null ? null : date.getTime();
    }
}
//然后将@TypeConverters注解添加到其他上面,即可以进行转换
If you put it on a Database, all Daos and Entities in that database will be able to use it.
If you put it on a Dao, all methods in the Dao will be able to use it.
If you put it on an Entity, all fields of the Entity will be able to use it.
If you put it on a POJO, all fields of the POJO will be able to use it.
If you put it on an Entity field, only that field will be able to use it.
If you put it on a Dao method, all parameters of the method will be able to use it.
If you put it on a Dao method parameter, just that field will be able to use it.

数据库的使用

new Thread(new Runnable() {//需要放在线程里面执行,因为这个是耗时操作
    @Override
    public void run() {
        User u = new User();
        u.setFirstName("fei");
        u.setLastName("ig");
        AppDatabase database= Room.databaseBuilder(getApplicationContext(),             AppDatabase.class, "ftmt")
                .build();
        database.userDao().insertAll(u);//插入
        User byName = database.userDao().findByName("fei", "ig");//查询
    }
}).start();

数据库的升级

//第一步,修改版本号,如要添加库的话要在entities里面添加新的表类,如下
@Database(entities = {User.class,Book.class},version = 2)
public abstract  class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();

    public abstract BookDao bookDao();
}
//第二步,新建需要添加的表的entities和dao,如果不需要新的表,这一步可以省略
//第三步,如下:
Migration MIGRATION_1_2 = new Migration(1, 2) {
            @Override
            public void migrate(SupportSQLiteDatabase database) {
//                    为旧表添加新的字段
//                    database.execSQL("ALTER TABLE User "
//                            + " ADD COLUMN book_id TEXT");
//                创建新的数据表
                database.execSQL("CREATE TABLE IF NOT EXISTS `book` (`book_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT)");
            }
        };
//升级数据库addMigrations(MIGRATION_1_2)
        Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "xulingyun")
                .addMigrations(MIGRATION_1_2)
                .build();

 

 

你可能感兴趣的:(android)