当前位置:网站首页>Use of room database

Use of room database

2022-07-05 05:19:00 Novice Xiaowang

1. Guide pack

implementation "androidx.room:room-runtime:2.4.2"
annotationProcessor "androidx.room:room-compiler:2.4.2"

2.gradle Middle configuration

javaCompileOptions {
    annotationProcessorOptions {
        arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
    }
}

3. Create data object entity

@Entity
public class User {

    @PrimaryKey(autoGenerate = true)
    long userId;
    @ColumnInfo(name = "username")
    String userName;
    @ColumnInfo(name = "password")
    String password;

    public User(@NonNull String userName,@NonNull String password){
        this.userName = userName;
        this.password = password;
    }
}

4. Create the corresponding Dao

@Dao
public interface UserDao {

    @Insert
    void addUser(User ... user);

    @Delete
    int deleteUser(User user);

    @Update
    int updateUser(User user);

    @Query("SELECT * FROM user WHERE userID = :id")
    User queryUser(long id);
}

5. Create database

//exportSchema = true  Support export Room Generated profile 
@Database(entities = {User.class},version = 3,exportSchema = true)
public abstract class MyRoomDatabase extends RoomDatabase {
    public static String roomName = "user";
    public static MyRoomDatabase instance;
    public abstract UserDao getUserDao();

    public static MyRoomDatabase getInstance(Context context){
        if (instance == null){
            synchronized (MyRoomDatabase.class){
                if (instance == null){
                    instance = Room.databaseBuilder(context,MyRoomDatabase.class,roomName).allowMainThreadQueries().build();
                }
            }
        }
        return instance;
    }
}

6. call

MyRoomDatabase.getInstance(this).getUserDao().addUser(new User("wang","lllll"));
原网站

版权声明
本文为[Novice Xiaowang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050512499724.html