Room是什么
Room是Google提供的一个ORM库。(ORM就是object relational mapping,对象关系映射。将关系型数据库转化为对象来进行处理)
Room主要组件
Database:创建,管理数据库,创建Dao对象。
Entity:实体类和数据库中的表对应。
DAO:data access objects,数据访问对象,定义访问数据库的方法。
如何使用Room
1.引入相关依赖到项目中
dependencies {
def room_version = "1.1.1"
implementation "android.arch.persistence.room:runtime:$room_version"
annotationProcessor "android.arch.persistence.room:compiler:$room_version" // use kapt for Kotlin
// optional - RxJava support for Room
implementation "android.arch.persistence.room:rxjava2:$room_version"
// optional - Guava support for Room, including Optional and ListenableFuture
implementation "android.arch.persistence.room:guava:$room_version"
// Test helpers
testImplementation "android.arch.persistence.room:testing:$room_version"
}
2.创建Entity
package com.architecture.demo.room;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.ForeignKey;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.Index;
import android.arch.persistence.room.PrimaryKey;
import android.text.TextUtils;
//指示数据表实体类
@Entity(tableName = "tb_student",//定义表名
indices = @Index(value = {"class_id", "number"}),//定义索引
foreignKeys = {@ForeignKey(entity = ClassEntity.class,
parentColumns = "id",
childColumns = "class_id")})//定义外键
public class StudentEntity {
@PrimaryKey(autoGenerate = true) //定义主键
public long id;
@ColumnInfo(name = "name")//定义数据表中的字段名
public String name;
@ColumnInfo(name = "number")
public int number;
@ColumnInfo(name = "class_id")
public String class_id;
@Ignore//指示Room需要忽略的字段或方法
public String ignoreText;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getClass_id() {
return class_id;
}
public void setClass_id(String class_id) {
this.class_id = class_id;
}
public String getIgnoreText() {
return ignoreText;
}
public void setIgnoreText(String ignoreText) {
this.ignoreText = ignoreText;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StudentEntity that = (StudentEntity) o;
return id == that.id &&
number == that.number &&
TextUtils.equals(name, that.name) &&
TextUtils.equals(class_id, that.class_id) &&
TextUtils.equals(ignoreText, that.ignoreText);
}
@Override
public String toString() {
return "StudentEntity{" +
"id=" + id +
", name='" + name + '\'' +
", number=" + number +
'}';
}
}
3.创建Dao
package com.architecture.demo.room;
import android.arch.paging.DataSource;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;
import java.util.List;
@Dao
public interface StudentDao {
@Query("SELECT * FROM tb_student ORDER BY number ASC")
List<StudentEntity> getAll();
@Query("SELECT * FROM tb_student LIMIT :current,:count ")
List<StudentEntity> getByLimit(int current, int count);
@Query("SELECT COUNT(*) FROM tb_student")
int getCount();
@Query("SELECT Max(number) FROM tb_student")
int getMaxNumber();
@Insert
void insert(StudentEntity... entities);
@Delete
void delete(StudentEntity entity);
@Query("DELETE FROM tb_student")
void deleteAll();
@Update
void update(StudentEntity entity);
@Query("SELECT * FROM tb_student ORDER BY number DESC")
DataSource.Factory<Integer, StudentEntity> loadStudent();
}
4创建Database
package com.architecture.demo.room;
import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import com.architecture.demo.util.CONSTANT;
@Database(entities = {ClassEntity.class, StudentEntity.class}, version = 1)
public abstract class DemoRoomDatabase extends RoomDatabase {
private static DemoRoomDatabase instance = null;
public static DemoRoomDatabase getInstance(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context, DemoRoomDatabase.class, "room_database").addCallback(new RoomDatabase.Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
Log.i(CONSTANT.TAG_ROOM, "onCreate:" + db.getPath());
}
@Override
public void onOpen(@NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
Log.i(CONSTANT.TAG_ROOM, "onOpen:" + db.getPath());
}
}).allowMainThreadQueries().build();
}
return instance;
}
public abstract StudentDao studentDao();
}
5.使用Room向插入数据,查找数据
package com.architecture.demo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.architecture.demo.paging.PagingFragment;
import com.architecture.demo.room.ClassDao;
import com.architecture.demo.room.ClassEntity;
import com.architecture.demo.room.DemoRoomDatabase;
import com.architecture.demo.room.StudentDao;
import com.architecture.demo.room.StudentEntity;
public class RoomAndPagingActivity extends AppCompatActivity implements View.OnClickListener {
DemoRoomDatabase mRoomDatabase;
private Button btn1;
private Button btn2;
private Button btn3;
private Button btn4;
public static int NUMBER;
PagingFragment mPagingFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room);
btn1 = findViewById(R.id.text1);
btn2 = findViewById(R.id.text2);
btn3 = findViewById(R.id.text3);
btn4 = findViewById(R.id.text4);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
mPagingFragment = PagingFragment.getInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.content_data, mPagingFragment);
fragmentTransaction.commit();
mRoomDatabase = DemoRoomDatabase.getInstance(getApplicationContext());
NUMBER = mRoomDatabase.studentDao().getMaxNumber();
}
@Override
public void onClick(View v) {
if (v == btn1) {
ClassDao classDao = mRoomDatabase.classDao();
ClassEntity classEntity = new ClassEntity();
classEntity.setName("三年二班");
classDao.insert(classEntity);
} else if (v == btn2) {
add10();
} else if (v == btn3) {
StudentDao studentDao = mRoomDatabase.studentDao();
StudentEntity student = getStudentEntity();
studentDao.insert(student);
} else if (v == btn4) {
StudentDao studentDao = mRoomDatabase.studentDao();
studentDao.deleteAll();
NUMBER = 0;
}
if (mPagingFragment != null) {
mPagingFragment.refreshData();
}
}
private void add10() {
for (int i = 0; i < 10; i++) {
StudentDao studentDao = mRoomDatabase.studentDao();
StudentEntity student = getStudentEntity();
studentDao.insert(student);
}
}
@NonNull
private StudentEntity getStudentEntity() {
NUMBER++;
StudentEntity student = new StudentEntity();
student.setName("小闹" + NUMBER);
student.setNumber(NUMBER);
student.setClass_id("1");
return student;
}
}
通过以上步骤既可完成Room的简单使用。
Demo地址:
https://github.com/CongYiMing/ArchitectureDemo