欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

JetPack 房间入门 - II,基本用法

最编程 2024-03-26 07:04:38
...

通过一个简单示例,演示Room如何生成数据库文件以及实现数据库的增删改查等操作。

2.1 依赖导入

    implementation "androidx.room:room-runtime:2.2.0"
    annotationProcessor "androidx.room:room-compiler:2.2.0" // For Java
    // 如果需要在调试时查看 Room 数据库的内容
    debugImplementation "androidx.room:room-testing:2.2.0"

2.2 Student 实体类定义

@Entity
public class Student {
    //主键SQL  唯一的autoGenerate自增长
    @PrimaryKey(autoGenerate = true)
    private int uid;

    @ColumnInfo(name = "name")
    private String name;

    @ColumnInfo(name = "pwd")
    private String pwd;

    @ColumnInfo(name = "address")
    private int address;

    public Student(String name, String pwd, int address) {
        this.name = name;
        this.pwd = pwd;
        this.address = address;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public void setAddress(int address) {
        this.address = address;
    }

    public int getUid() {
        return uid;
    }

    public String getName() {
        return name;
    }

    public String getPwd() {
        return pwd;
    }

    public int getAddress() {
        return address;
    }

    @Override
    public String toString() {
        return "Student{" +
                "uid=" + uid +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

2.3 StudentDao 操作接口类

@Dao
public interface StudentDao {

    @Insert
    void insert(Student... student);

    @Delete
    void delete(Student student);

    @Update
    void update(Student student);

    @Query("select * from Student")
    List<Student> getall();

    //查询一条
    @Query("select * from Student where name like:name")
    Student findByName(String name);


    //查询数组多个记录
    @Query("select * from Student where uid in(:userIds)")
    List<Student> getallId(int[] userIds);

}

2.4 StudentDataBase 类

//exportSchema 导出模式
@Database(entities = {Student.class}, version = 1, exportSchema = false)
public abstract class StudentDataBase extends RoomDatabase {
    //暴露DAO
    public abstract StudentDao userDao();
    
}

2.5 RoomTestActivity 类

public class RoomTestActivity extends AppCompatActivity {

    ActivityViewmodelBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityViewmodelBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        //数据库的操作应该是在子线程
        DbTest t = new DbTest();
        t.start();
    }

    //测试刚刚写的三个角色Room数据库  增删改查
    class DbTest extends Thread {
        @Override
        public void run() {
            super.run();
            //数据库的操作都在这里
            StudentDataBase henryDB = Room.databaseBuilder
                    (getApplicationContext(), StudentDataBase.class, "Henry")
                    .allowMainThreadQueries()//可以在主线程执行查询,不建议这么做
                    .fallbackToDestructiveMigration()//数据库改变时,强制升级时,不报错
                    .build();
            StudentDao dao = henryDB.userDao();

            dao.insert(new Student("henry0", "123", 1));
            dao.insert(new Student("henry1", "456", 2));
            dao.insert(new Student("henry2", "789", 3));
            dao.insert(new Student("henry3", "101112", 4));

            //查看全部数据
            List<Student> all = dao.getall();
            Log.d("Henry00", "all = " + all.toString());
            Log.d("Henry00", "---------------------------------");
            //查询名字为henry1的一条数据
            Student henry1 = dao.findByName("henry1");
            Log.d("Henry00", "henry1 查询 = " + henry1.toString());
            Log.d("Henry00", "---------------------------------");

            //查询id为2,3,4的数组数据
            List<Student> allID = dao.getallId(new int[]{2, 3, 4});
            Log.d("Henry00", "allID 查询 = " + allID.toString());
        }

    }
}

输出:

在这里插入图片描述

使用Android Studio DB Browser插件查看数据库信息
在这里插入图片描述