当前位置:网站首页>room数据库的使用

room数据库的使用

2022-07-05 05:13:00 菜鸟xiaowang

1.导包

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

2.gradle中配置

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

3.创建数据对象实体

@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.创建对应的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.创建数据库

//exportSchema = true 支持导出Room生成的配置文件
@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.调用

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

版权声明
本文为[菜鸟xiaowang]所创,转载请带上原文链接,感谢
https://blog.csdn.net/xiaowang_lj/article/details/125603979