【android学习】Jetpack:Room数据库

简介

google公司推出的一款类似GreenDao、OrmLite的数据库框架

添加依赖

dependencies {
    implementation 'android.arch.persistence.room:runtime:2.2.0'
    annotationProcessor 'android.arch.persistence.room:compiler:2.2.0'
    //添加测试支持
    implementation 'android.arch.persistence.room:testing:2.2.0'
}

具体实现

History.java

  1. @Entity 创建数据库表
  2. @PrimaryKey(autoGenerate = true) 主键 自增长
  3. @ColumnInfo 数据库表中的字段名
  4. @Ignore 这个字段不会在数据库中创建字段
  5. 这里是必须要创建set  get 方法的
@Entity
public class History {
    @PrimaryKey(autoGenerate = true)
    private int id;
    @ColumnInfo(name = "type")
    private String type;
    @ColumnInfo(name = "result")
    private String result;
    @ColumnInfo(name = "time")
    private String time;
    //这个用来表示下面的字段不是数据库的字段,只是临时数据
    @Ignore
    private int i;
    public History(String type, String result, String time) {
        this.type = type;
        this.result = result;
        this.time = time;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "History{" +
                "id=" + id +
                ", type='" + type + '\'' +
                ", result='" + result + '\'' +
                ", time='" + time + '\'' +
                '}';
    }
}

 HistoryDao.java

  1. @Dao是Room中的主要组件,负责定义访问数据库的方法
  2. @Insert 数据库插入方法
  3.  @Delete 删除方法
  4.  @Update修改方法
  5. @Query 查询方法
  6. :historyIds 这里的参数,代表的是方法中传入的变量
  7. '%' || :result  || '%'   模糊查询的拼接
@Dao
public interface HistoryDao {

    @Insert
    void insert(History... histories);

    @Delete
    void delete(History history);

    @Update
    void update(History history);

    @Query("select * from History")
    List getAll();

    @Query("select * from History where id in (:historyIds)")
    List getAllId(int[] historyIds);


    //模糊查询
    @Query("select * from History where result like '%' || :result  || '%'")
    List getByResult(String result);
}

 AppDatabase .java

  1. @Database 这个组件创建一个数据库
  2. entities数据库中包含哪些表,结合@Entity使用
  3. version 版本号,和数据库升级相关
/**
 * 定义数据库
 */
@Database(entities = {History.class},version = 1)
public abstract class AppDatabase extends RoomDatabase {
    //数据库名称
    private static final String DB_NAME = "UserDatabase.db";
    private static volatile AppDatabase instance;

    public static synchronized AppDatabase getInstance(Context context) {
        if (instance == null) {
            instance = create(context);
        }
        return instance;
    }

//创建数据库
    private static AppDatabase create(final Context context) {
        return Room.databaseBuilder(
                context,
                AppDatabase.class,
                DB_NAME).build();
    }
//获得user的数据库实例
    public abstract HistoryDao historyDao();
}

数据库的使用

数据库插入

    class InsterThread extends Thread {
        @Override
        public void run() {
            super.run();
            History history = new History("张三" + index, "text" + index, DateUtils.dateToStrLong(new Date()));
            Log.d(TAG, "---插入---" + history);
            AppDatabase.getInstance(MainActivity.this).historyDao().insert(history);
            index++;
        }
    }

数据库删除

    class DeleteThread extends Thread {
        @Override
        public void run() {
            super.run();
            History history = new History("张三" + index, "text" + index, DateUtils.dateToStrLong(new Date()));
            history.setId(3);
            Log.d(TAG, "--修改--" + history.toString());
            AppDatabase.getInstance(MainActivity.this).historyDao().delete(history);
            index++;
        }
    }

数据库修改

   class UpdateThread extends Thread {
        @Override
        public void run() {
            super.run();
            History history = new History("李四" + index, "text" + index, DateUtils.dateToStrLong(new Date()));
            history.setId(2);
            Log.d(TAG, "--修改--" + history.toString());
            AppDatabase.getInstance(MainActivity.this).historyDao().update(history);
            index++;
        }
    }

数据库查询

   class SelectThread extends Thread {
        @Override
        public void run() {
            super.run();

            List all = AppDatabase.getInstance(MainActivity.this).historyDao().getAll();
            for (History history : all) {
                Log.d(TAG, "----查询----" + history.toString());
            }
        }
    }

模糊查询

    class LikeSelectThread extends Thread {
        @Override
        public void run() {
            super.run();
            List all = AppDatabase.getInstance(MainActivity.this).historyDao().getByResult("2");
            for (History history : all) {
                Log.d(TAG, "----模糊查询----" + history.toString());
            }

        }
    }

条件查询

    class WhereSelectThread extends Thread {
        @Override
        public void run() {
            super.run();
            int[] ids = new int[]{1,3,5};
            List allId = AppDatabase.getInstance(MainActivity.this).historyDao().getAllId(ids);
            for (History history : allId) {
                Log.d(TAG, "----条件查询----" + history.toString());
            }

        }
    }

总结

  • 数据库增,删,改,查必须在线程中操作
  • sql语句的拼接用的 || 符号
  • entity必须要创建set  get 方法

demo下载

你可能感兴趣的:(android学习)