JetPack------ROOM

https://developer.android.google.cn/jetpack/androidx/releases/room

https://developer.android.google.cn/training/data-storage/room

1、引入room

implementation "androidx.room:room-runtime:2.2.5"
    annotationProcessor "androidx.room:room-compiler:2.2.5"
    testImplementation "androidx.room:room-testing:2.2.5"

2、创建bean类

package com.yuanxuzhen.room;

import androidx.annotation.NonNull;
import androidx.room.Entity;


@Entity(tableName = "user", primaryKeys = {"id"})
public class UserData {
   public long id;
   public String name;
   public int age;

   @Override
   public String toString() {
      return "UserData{" +
              "id=" + id +
              ", name='" + name + '\'' +
              ", age=" + age +
              '}';
   }
}
package com.yuanxuzhen.room;

import androidx.room.Entity;


@Entity(tableName = "student", primaryKeys = {"id"})
public class StudentData {
   public long id;
   public String name;
   public int age;

   @Override
   public String toString() {
      return "StudentData{" +
              "id=" + id +
              ", name='" + name + '\'' +
              ", age=" + age +
              '}';
   }
}
@Entity(tableName = "student", primaryKeys = {"id"}) 

代表当前bean对应的表示student,主键是id

3、创建dao

package com.yuanxuzhen.room;


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 UserDao {
    @Query("select * from user")
    List<UserData> qeuryAll();

    @Query("select * from user where id = :id")
    UserData getAttachement(long id);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    List<Long> insert(UserData... data);

    @Delete
    int delete(UserData data);

    @Delete
    int delete(List<UserData> list);

    @Update
    int update(UserData data);

}
package com.yuanxuzhen.room;


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 {
    @Query("select * from student")
    List<StudentData> qeuryAll();

    @Query("select * from student where id = :id")
    StudentData getData(long id);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    List<Long> insert(StudentData... data);

    @Delete
    int delete(StudentData data);

    @Delete
    int delete(List<StudentData> list);

    @Update
    int update(StudentData data);

}

4、数据库

package com.yuanxuzhen.room;

import androidx.room.Database;
import androidx.room.RoomDatabase;


@Database(entities = {UserData.class, StudentData.class},
        version = 1)
public abstract class YuanDateBase extends RoomDatabase {
    public abstract UserDao getUserDao();
    public abstract StudentDao getStudentDao();
}
@Database(entities = {UserData.class, StudentData.class},
        version = 1)

代表创建user表和student表,数据库版本1

5、单例获取数据库

package com.yuanxuzhen.room;

import android.content.Context;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;


public class DateBaseManager {


    private static volatile YuanDateBase dateBase;

    public static YuanDateBase getDataBase(Context context) {
        if(dateBase == null){
            synchronized (DateBaseManager.class) {
                if(dateBase == null){
                    dateBase = Room.databaseBuilder(context.getApplicationContext(),
                            YuanDateBase.class,
                            "yuan").build();
                }
            }
        }
        return dateBase;
    }


}

6、对dao进行封装,方便调用

package com.yuanxuzhen.room;

import android.content.Context;

import androidx.recyclerview.widget.ListUpdateCallback;

import java.util.List;

public class YuanDataUtil {
    public static List<UserData> getUserList(Context context){
        YuanDateBase dateBase = DateBaseManager.getDataBase(context);
        UserDao dao = dateBase.getUserDao();
        return dao.qeuryAll();
    }

    public static void insertUser(Context context, List<UserData> list){
        if(list == null || list.size() == 0){
            return;
        }
        YuanDateBase dateBase = DateBaseManager.getDataBase(context);
        UserDao dao = dateBase.getUserDao();
        UserData[] array = new UserData[list.size()];
        int i = 0;
        for(UserData data : list){
            array[i] = data;
            ++i;
        }
        dao.insert(array);
    }

    public static List<StudentData> getStudentList(Context context){
        YuanDateBase dateBase = DateBaseManager.getDataBase(context);
        StudentDao dao = dateBase.getStudentDao();
        return dao.qeuryAll();
    }

    public static void insertStudent(Context context, List<StudentData> list){
        if(list == null || list.size() == 0){
            return;
        }
        YuanDateBase dateBase = DateBaseManager.getDataBase(context);
        StudentDao dao = dateBase.getStudentDao();
        StudentData[] array = new StudentData[list.size()];
        int i = 0;
        for(StudentData data : list){
            array[i] = data;
            ++i;
        }
        dao.insert(array);
    }
}

7测试

package com.yuanxuzhen.jetpackdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import com.yuanxuzhen.room.StudentData;
import com.yuanxuzhen.room.UserData;
import com.yuanxuzhen.room.YuanDataUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {
    ExecutorService mService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mService = Executors.newCachedThreadPool();
        mService.execute(new Runnable() {
            @Override
            public void run() {
                List<UserData> list = new ArrayList<>();
                for(int i = 0; i < 5; i++){
                    UserData userData = new UserData();
                    userData.id = i;
                    userData.name = "user" + i;
                    userData.age = 20 + i;
                    list.add(userData);
                }
                YuanDataUtil.insertUser(MainActivity.this, list);

                List<StudentData> studentList = new ArrayList<>();
                for(int i = 10; i < 15; i++){
                    StudentData data = new StudentData();
                    data.id = i;
                    data.name = "student" + i;
                    data.age = 10 + i;
                    studentList.add(data);
                }
                YuanDataUtil.insertStudent(MainActivity.this, studentList);


                List<UserData> queryList = YuanDataUtil.getUserList(MainActivity.this);
                List<StudentData> queryStudentList = YuanDataUtil.getStudentList(MainActivity.this);

                for(UserData data : queryList){
                    Log.e("yuan", "" + data);
                }

                for(StudentData data : queryStudentList){
                    Log.e("yuan", "" + data);
                }
            }
        });


    }
}

数据库操作要放在子线程中。

结果

2021-07-15 12:20:33.607 31816-31857/com.yuanxuzhen.jetpackdemo E/yuan: UserData{id=0, name='user0', age=20}
2021-07-15 12:20:33.607 31816-31857/com.yuanxuzhen.jetpackdemo E/yuan: UserData{id=1, name='user1', age=21}
2021-07-15 12:20:33.607 31816-31857/com.yuanxuzhen.jetpackdemo E/yuan: UserData{id=2, name='user2', age=22}
2021-07-15 12:20:33.607 31816-31857/com.yuanxuzhen.jetpackdemo E/yuan: UserData{id=3, name='user3', age=23}
2021-07-15 12:20:33.607 31816-31857/com.yuanxuzhen.jetpackdemo E/yuan: UserData{id=4, name='user4', age=24}
2021-07-15 12:20:33.607 31816-31857/com.yuanxuzhen.jetpackdemo E/yuan: StudentData{id=10, name='student10', age=20}
2021-07-15 12:20:33.608 31816-31857/com.yuanxuzhen.jetpackdemo E/yuan: StudentData{id=11, name='student11', age=21}
2021-07-15 12:20:33.608 31816-31857/com.yuanxuzhen.jetpackdemo E/yuan: StudentData{id=12, name='student12', age=22}
2021-07-15 12:20:33.608 31816-31857/com.yuanxuzhen.jetpackdemo E/yuan: StudentData{id=13, name='student13', age=23}
2021-07-15 12:20:33.608 31816-31857/com.yuanxuzhen.jetpackdemo E/yuan: StudentData{id=14, name='student14', age=24}

上一篇:这才是做了五年Android开发该有的样子!


下一篇:15个经典面试问题,阿里巴巴内部Jetpack宝典意外流出