Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Android Room

Android使用Room操作数据库流程详解

作者:Flynn_MIMD

谷歌推荐使用Room操作数据库,Room在 SQLite 上提供了一个抽象层,在充分利用 SQLite强大功能的同时,能够流畅地访问数据库

Room的三个主要组件:

build.gradle添加

dependencies {
    def room_version = "2.4.3"

    implementation "android.arch.persistence.room:runtime:$room_version"
    annotationProcessor "android.arch.persistence.room:compiler:$room_version" 

    implementation "android.arch.persistence.room:rxjava2:$room_version"

    testImplementation "android.arch.persistence.room:testing:$room_version"
}

1. 创建实体类User

@Entity(tableName = "users")
public class User {
    @PrimaryKey
    public int uid;
    @ColumnInfo(name = "first_name")
    public String firstName;
    @ColumnInfo(name = "last_name")
    public String lastName;
}

@Entity实体类,users表的名称,不加默认user

@ColumnInfo列名

@PrimaryKey主键

2. 创建DAO

@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List<User> getAll();
    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    List<User> loadAllByIds(int[] userIds);
    @Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
            "last_name LIKE :last LIMIT 1")
    User findByName(String first, String last);
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertAll(User... users);
    @Delete
    void delete(User user);
}

增,删,改:将实例与表的主键进行匹配

查询结果将自动映射到对应类型的字段,若未映射将报警告

3. 数据库

抽象类AppDatabase 定义数据库配置,并作为应用对持久性数据的主要访问点,扩展了RommDataBase

@Database(entities = {User.class}, version = 1, exportSchema = false)
public abstract class AppDataBase extends RoomDatabase {
    public abstract UserDao userDao();
}

4. 使用

AppDataBase db = Room.databaseBuilder(getApplicationContext(),
                        AppDataBase.class, "database-name").build();
                for (int i = 0; i < 10; i++) {
                    User user = new User();
                    user.uid = i;
                    user.firstName = "Shell" + i;
                    user.lastName = "Hub" + i;
                    db.userDao().insertAll( user);
                    List<User> userList = db.userDao().getAll();
                    for(User user1 : userList) {
                        Log.d("mip",""+user1.firstName);
                    }
                }

为了节约获取数据库的时间和资源,采取单例模式

简单实现:

public class Utils {
    private static AppDataBase db = null;
    private static Context context = null;
    public static AppDataBase getDb(){
        if( db == null) {
            db = Room.databaseBuilder(context,
                    AppDataBase.class, "database-name").build();
        }
        return db;
    }
    public static void setContext(Context context){
        Utils.context = context;
    }
}

调用

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Utils.setContext(getApplicationContext());
        new Thread(new Runnable() {
            @Override
            public void run() {
                AppDataBase db = Utils.getDb();
                for (int i = 0; i < 10; i++) {
                    User user = new User();
                    user.uid = i;
                    user.firstName = "Shell" + i;
                    user.lastName = "Hub" + i;
                    db.userDao().insertAll( user);
                    List<User> userList = db.userDao().getAll();
                    for(User user1 : userList) {
                        Log.d("mip",""+user1.firstName);
                    }
                }
            }
        }).start();
    }
}

路过的大佬们有更好的单例实现请告诉我一下,

到此这篇关于Android使用Room操作数据库流程详解的文章就介绍到这了,更多相关Android Room内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文