人生何须万种愁,千里云烟一笑收
一,定义
Room也是一个ORM框架,它在SQLite上提供了一个抽象层,屏蔽了部分底层的细节,使用对象对数据库进行操作,进行CRUD就像对象调用方法一样的简单。
二,角色介绍
谷歌官方给出了一张图片,可以更加直观的了解Room的组成部分:
从上图可以看出,Room主要由三部分组成:
1,Room Database 数据库:底层连接的主要接入点,创建数据库就靠它了
2,Data Access Objects DAO:在DAO中会有一系列对数据库进行CRUD的方法声明
3,Entity 实体类:是对象与数据表的对应表现,设计实体类,并最后转化为对应的数据表
可以这么理解,我们通过实体类的中Getter和Setter方法对数据进行变更操作,然后Room Database使用DAO中的方法,对表中的数据进行对应的操作。从而屏蔽了繁琐的数据库原生操作。当然这其中使用了注解进行功能的标注。
三,基本使用
1,在app的build.gradle里面添加依赖:
def room_version = "2.2.6"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version" // use kapt for Kotlin
// optional - RxJava support for Room
implementation "androidx.room:room-rxjava2:$room_version"
// optional - Guava support for Room, including Optional and ListenableFuture
implementation "androidx.room:room-guava:$room_version"
// Test helpers
testImplementation "androidx.room:room-testing:$room_version"
2,创建表Entity:
@Entity
public class YuanZhen {
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name ="name")
private String name;
@ColumnInfo(name ="age")
private int age;
@ColumnInfo(name ="address")
private String address;
@Ignore
private String sex;
public YuanZhen(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
@Override
public String toString() {
return "YuanZhen{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
'}';
}
}
上面其中几个注解的含义:
①,@Entity 表示数据库中的表
②,@PrimaryKey 表示主键,autoGenerate 表示自增
③,@ColumnInfo 表示字段,name 表示字段名称
④,@Ignore 表示一个属性不加入生成表的字段,只是临时使用
3,创建Dao:
@Dao
public interface YuanZhenDao {
@Insert
void insert(YuanZhen... yuanzhens);
@Delete
void delete(YuanZhen yuanZhen);
@Update
void update(YuanZhen yuanZhen);
@Query("select * from YuanZhen")
List<YuanZhen> getAll();
}
这里面包含了增上改查。
其中几个注解的含义:
①,@Dao 表示访问 DB 的方法,需要声明为接口或抽象类,编译阶段将生成 _Impl 实现类,此处则将生成 YuanZhenDao_Impl.java 文件
②,@Insert、@Delete、@Update 、 @Query 分别表示数据库的增删改查方法
4,创建Room Database 数据库:
@Database(entities = {YuanZhen.class},version = 1,exportSchema = false)
public abstract class MyDatabase extends RoomDatabase {
public abstract YuanZhenDao yuanZhenDao();
}
其中几个注解的含义:
①,@Database:表示数据库的定义
②,entities: 表示数据库中包含的表
③,version:表示数据库版本号
5,使用:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
MyDatabase myDatabase = Room.databaseBuilder(getApplicationContext(),MyDatabase.class,"YuanZhenDb").build();
YuanZhenDao yuanZhenDao = myDatabase.yuanZhenDao();
yuanZhenDao.insert(new YuanZhen("yz",20,"淄博市"));
yuanZhenDao.insert(new YuanZhen("yz1",22,"淄博市"));
List<YuanZhen> all = yuanZhenDao.getAll();
System.out.println("输出:"+all.toString());
}
}).start();
}
}
输出结果:
I/System.out: 输出:[YuanZhen{id=1, name='yz', age=20, address='淄博市', sex='null'}, YuanZhen{id=2, name='yz1', age=22, address='淄博市', sex='null'}, YuanZhen{id=3, name='yz', age=20, address='淄博市', sex='null'}
这就是基本使用。
四,条件查询
如果我们想查询某一条数据的话,需要在dao里面增加条件查询:
@Dao
public interface YuanZhenDao {
@Insert
void insert(YuanZhen... yuanzhens);
@Delete
void delete(YuanZhen yuanZhen);
@Update
void update(YuanZhen yuanZhen);
@Query("select * from YuanZhen")
List<YuanZhen> getAll();
@Query("select * from YuanZhen where name like :name")
YuanZhen getByName(String name);
@Query("select * from YuanZhen where age in(:ages)")
List<YuanZhen> getByAges(int[] ages);
}
使用:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
MyDatabase myDatabase = Room.databaseBuilder(getApplicationContext(),MyDatabase.class,"YuanZhenDb").build();
YuanZhenDao yuanZhenDao = myDatabase.yuanZhenDao();
yuanZhenDao.insert(new YuanZhen("yz",20,"淄博市"));
yuanZhenDao.insert(new YuanZhen("yz1",22,"淄博市"));
YuanZhen yz = yuanZhenDao.getByName("yz");
System.out.println("输出ByName:"+yz.toString());
int[] ages ={20,22};
List<YuanZhen> byAges = yuanZhenDao.getByAges(ages);
System.out.println("输出ByAges:"+byAges.toString());
}
}).start();
}
}
输出:
I/System.out: 输出ByName:YuanZhen{id=1, name='yz', age=20, address='淄博市', sex='null'}
I/System.out: 输出ByAges:[YuanZhen{id=1, name='yz', age=20, address='淄博市', sex='null'}, YuanZhen{id=2, name='yz1', age=22, address='淄博市', sex='null'}
如果只想查姓名和地址,那么可以新建一个类:
public class YuanZhenNew {
@ColumnInfo(name = "name")
public String name;
@ColumnInfo(name = "address")
public String address;
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public YuanZhenNew(String name, String address) {
this.name = name;
this.address = address;
}
@Override
public String toString() {
return "YuanZhenNew{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
在dao中查询:
@Dao
public interface YuanZhenDao {
@Insert
void insert(YuanZhen... yuanzhens);
@Delete
void delete(YuanZhen yuanZhen);
@Update
void update(YuanZhen yuanZhen);
@Query("select * from YuanZhen")
List<YuanZhen> getAll();
@Query("select * from YuanZhen where name like :name")
YuanZhen getByName(String name);
@Query("select * from YuanZhen where age in(:ages)")
List<YuanZhen> getByAges(int[] ages);
@Query("select name,address from YuanZhen ")
public List<YuanZhenNew> getNew();
}
使用:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
MyDatabase myDatabase = Room.databaseBuilder(getApplicationContext(),MyDatabase.class,"YuanZhenDb").build();
YuanZhenDao yuanZhenDao = myDatabase.yuanZhenDao();
yuanZhenDao.insert(new YuanZhen("yz",20,"淄博市"));
yuanZhenDao.insert(new YuanZhen("yz1",22,"淄博市"));
List<YuanZhenNew> aNew = yuanZhenDao.getNew();
System.out.println("输出aNew:"+aNew.toString());
}
}).start();
}
}
输出:
I/System.out: 输出aNew:[YuanZhenNew{name='yz', address='淄博市'}, YuanZhenNew{name='yz1', address='淄博市'}]
更多高级用法下章继续讲解