第三章:Room數據庫使用

  • 導入依賴

    //room數據庫
    implementation 'androidx.room:room-runtime:2.2.5'
    annotationProcessor "androidx.room:room-compiler:2.2.5"
  • 構建數據庫字段
package cn.yumakeji.jetpackroomstudy;

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;

/**
 * 表名
 * tableName = "cache"
 * <p></p>
 * 本表中 那些字段 不需要 映射到表中
 * ignoredColumns = {"data"}
 */
@Entity(tableName = "user_info", ignoredColumns = {"num1", "num3"})
public class Student {

    //PrimaryKey 必須要有,且不爲空,autoGenerate 主鍵的值是否由Room自動生成,默認false
    @PrimaryKey(autoGenerate = true)
    public int id;

    //指定該字段在表中的列的名字
    @ColumnInfo(name = "name")
    public String name;

    //@ColumnInfo:表中的字段,默認用下面的字段名age
    @ColumnInfo
    public int age;

    //忽略該字段
    @Ignore
    public String studyNum;
    @ColumnInfo
    public String num1;
    @ColumnInfo
    public String num2;
    @ColumnInfo
    public String num3;


    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", studyNum='" + studyNum + '\'' +
                ", num1='" + num1 + '\'' +
                ", num2='" + num2 + '\'' +
                ", num3='" + num3 + '\'' +
                '}';
    }
}

  • 創建增刪改查
package cn.yumakeji.jetpackroomstudy;

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;

import java.util.List;

@Dao
public interface StudentDao {
    /**
     * OnConflictStrategy.REPLACE :直接覆蓋
     *
     * @param students
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insert(Student... students);

    //只能傳遞對象的,刪除時根據Student中的主鍵 來比對的
    @Delete
    void delete(Student... student);

    //只能傳遞對象的,更新時根據Student中的主鍵 來比對的
    @Update(onConflict = OnConflictStrategy.REPLACE)
    void update(Student... student);

    //獲取表中所有數據
    @Query("select * from user_info")
    List<Student> findAll();

    //根據name來查找數據(這裏是一對一,如果是一對多,這裏可以寫List<Student>)
    @Query("select * from user_info where name = :name")
    Student findByName(String name);

    //根據name來查找數據(這裏是一對多,如果是一對一,這裏可以寫Student)
    @Query("select * from user_info where age = :age")
    List<Student> findByAge(int age);

    /**
     * 注意,冒號後面必須緊跟參數名,中間不能有空格。大於小於號和冒號中間是有空格的。
     * select *from cache where【表中列名】 =:【參數名】------>等於
     * where 【表中列名】 < :【參數名】 小於
     * where 【表中列名】 between :【參數名1】 and :【參數2】------->這個區間
     * where 【表中列名】like :參數名----->模糊查詢
     * where 【表中列名】 in (:【參數名集合】)---->查詢符合集合內指定字段值的記錄
     *
     * @param ids
     * @return
     */
    //查找參數集合
    @Query("select * from user_info where id in (:ids)")
    List<Student> findByIds(int[] ids);

}

  • 創建數據庫

import cn.yumakeji.jetpackroomstudy.global.AppGlobals;

@Database(entities = {Student.class}, version = 1)
public abstract class RoomDataBase extends RoomDatabase {
    private static final RoomDataBase database;

    static {
        //創建一個內存數據庫
        //但是這種數據庫的數據只存在於內存中,也就是進程被殺之後,數據隨之丟失
        //Room.inMemoryDatabaseBuilder()
        database = Room.databaseBuilder(AppGlobals.getApplication(), RoomDataBase.class, "jetpack_demo")
                //是否允許在主線程進行查詢
                .allowMainThreadQueries()
                //數據庫創建和打開後的回調
                //.addCallback()
                //設置查詢的線程池
                //.setQueryExecutor()
                //.openHelperFactory()
                //room的日誌模式
                //.setJournalMode()
                //數據庫升級異常之後的回滾
                //.fallbackToDestructiveMigration()
                //數據庫升級異常後根據指定版本進行回滾
                //.fallbackToDestructiveMigrationFrom()
                //數據庫升級的入口(如果沒有配置升級的時候會將數據庫內容全部清除)
                // .addMigrations(CacheDatabase.sMigration)
                .build();
    }

    /**
     * 獲取Student數據庫操作對象
     *
     * @return
     */
    public abstract StudentDao getStudentDao();

    public static RoomDataBase get() {
        return database;
    }

    /**
     * 數據庫升級的入口(如果沒有配置升級的時候會將數據庫內容全部清除)
     */
//    static Migration sMigration = new Migration(1, 3) {
//        @Override
//        public void migrate(@NonNull SupportSQLiteDatabase database) {
//            database.execSQL("alter table teacher rename to student");
//            database.execSQL("alter table teacher add column teacher_age INTEGER NOT NULL default 0");
//        }
//    };
}

  • 使用
    在這裏插入圖片描述

public class MainActivity extends AppCompatActivity {

    private List<Student> mList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        for (int i = 0; i < 10; i++) {
            Student student = new Student();
            student.name = "huangxiaoguo" + i;
            student.age = 18 + i;
            student.num1 = String.valueOf(Math.round(Math.random() * 10) + 1);
            student.num2 = String.valueOf(Math.round(Math.random() * 10) * 10 + 10);
            student.num3 = String.valueOf(Math.round(Math.random() * 10) * 10 + 20);
            mList.add(student);
        }
    }

    /**
     * 增加數據
     *
     * @param view
     */
    public void onInsertClick(View view) {
        for (Student student : mList) {
            RoomDataBase.get().getStudentDao().insert(student);
        }
        /**
         * 多個插入
         */
        RoomDataBase.get().getStudentDao().insert(mList.get(2),mList.get(3),mList.get(4),mList.get(5));
    }

    /**
     * 單條刪除數據
     *
     * @param view
     */
    public void onDeleteOneClick(View view) {
        Student student = RoomDataBase.get().getStudentDao().findByName("huangxiaoguo1");
        if (student==null){
            return;
        }
        RoomDataBase.get().getStudentDao().delete(student);
    }

    /**
     * 刪除所有數據
     * @param view
     */
    public void onDeleteAllClick(View view) {
        List<Student> all = RoomDataBase.get().getStudentDao().findAll();
        for (Student student : all) {
            RoomDataBase.get().getStudentDao().delete(student);
        }
    }
    /**
     * 單條更新數據
     *
     * @param view
     */
    public void onUpDataOneClick(View view) {
        Student student = RoomDataBase.get().getStudentDao().findByName("huangxiaoguo5");
        if (student==null){
            return;
        }
        student.name="修改了";
        RoomDataBase.get().getStudentDao().update(student);
    }

    /**
     * 獲取所有數據
     *
     * @param view
     */
    public void onGetAllClick(View view) {
        List<Student> all = RoomDataBase.get().getStudentDao().findAll();
        if (all==null||all.size()==0){
            Log.e("TTT","沒有查詢到數據");
            return;
        }
        for (Student student : all) {
            Log.e("TTT",student.toString());
        }
    }

    /**
     * 一對一查詢數據
     *
     * @param view
     */
    public void onFindOneByOneClick(View view) {
        Student student = RoomDataBase.get().getStudentDao().findByName("huangxiaoguo3");
        if (student==null){
            return;
        }
        Log.e("TTT",student.toString());
    }

    /**
     * 一對多查詢數據
     *
     * @param view
     */
    public void onFindOneBySomeClick(View view) {
        List<Student> list = RoomDataBase.get().getStudentDao().findByAge(22);
        Log.e("TTT",list.toString());
    }

    /**
     * 查詢符合集合內數據(String)
     *
     * @param view
     */
    public void onFindInSomeIntClick(View view) {
        List<Student> list = RoomDataBase.get().getStudentDao().findByIds(new int[]{7, 8, 9});
        Log.e("TTT",list.toString());
    }

}

完成

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章