Website: developer. The android. Google. Cn/training/da…
Room provides an abstraction layer on TOP of SQLite to allow smooth database access while taking full advantage of SQLite’s power.
Room contains three important parts:
- Database: Contains the database holder and serves as the primary access point for the underlying connection that applies retained persistent relational data.
- Entity: represents a table in the database.
- DAO: Contains methods for accessing the database.
Basic steps:
1. Import the configuration
Dependencies {def room_version = "2.2.5" implementation androidx. Room: room-Runtime :$room_version" annotationProcessor "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor // optional - Kotlin Extensions and Coroutines support for Room implementation "androidx.room:room-ktx:$room_version" // optional - RxJava support for Room implementation "androidx.room:room-rxjava2:$room_version" // optional - Guava support for Room, including Optional and ListenableFuture implementation "androidx.room:room-guava:$room_version" // Test helpers testImplementation "androidx.room:room-testing:$room_version" }Copy the code
2, create table
@Entity
public class User {
@PrimaryKey
public int uid;
@ColumnInfo(name = "first_name")
public String firstName;
@ColumnInfo(name = "last_name")
public String lastName;
}
Copy the code
Reference: developer. The android. Google. Cn/training/da…
Create Dao
Contains a list of methods to access the database.
@Dao
public interface UserDao {
@Query("SELECT * FROM user")
List<User> getAll(a);
@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);
@Insert
void insert(User user);
@Delete
void delete(User user);
}
Copy the code
Reference: developer. The android. Google. Cn/training/da…
4, create database
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao(a);
}
Copy the code
5, use
AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "database-name").build();
db.userDao().insert(new User());
Copy the code