- 导入依赖
//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());
}
}
完成