Post

【Android】使用Room连接SQLite数据库

1.在app/build.gradle中添加依赖

1
2
implementation 'android.arch.persistence.room:runtime:1.1.1'
annotationProcessor 'android.arch.persistence.room:compiler:1.1.1' 

2.定义实体类

1
2
3
4
5
6
7
8
9
10
11
@Entity
public class User {
    @PrimaryKey
    public int uid;

    @ColumnInfo(name = "first_name")
    public String firstName;

    @ColumnInfo(name = "last_name")
    public String lastName;
}

3.定义DAO(即Repository)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@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
    void insertAll(User... users);

    @Delete
    void delete(User user);
}

4.定义数据库

由于创建RoomDatabase实例的成本相当高,因此官方推荐使用单例模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Database(entities = {User.class}, version = 1)
public abstract class SampleDatabase extends RoomDatabase {
    /** The only instance */
    private static SampleDatabase sInstance;

    public static synchronized SampleDatabase getInstance(Context context) {
        if (sInstance == null) {
            sInstance = Room
                    .databaseBuilder(context.getApplicationContext(), SampleDatabase.class, "database-name")
                    .build();
        }
        return sInstance;
    }

    public static void closeInstance() {
        if (sInstance != null) {
            sInstance.close();
            sInstance = null;
    }

    public abstract UserDao userDao();

}
This post is licensed under CC BY 4.0 by the author.