اتاق – استراحت


! . کاربر شی:

وابستگی ها .gradle .

    // Room components
    implementation "android.arch.persistence.room:runtime:$roomComponentsVersion"
    annotationProcessor "android.arch.persistence.room:compiler:$roomComponentsVersion"

    // Lifecycle components
    implementation "android.arch.lifecycle:extensions:$lifecycleComponentsVersion"
    annotationProcessor "android.arch.lifecycle:compiler:$lifecycleComponentsVersion"

کاربر کلاس شی.

@Entity
public class User {
    @PrimaryKey
    public int uid;

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

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

رابط کاربری UserDao.

@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List getAll();

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    List 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);
}

پرس و جو.

:

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase INSTANCE;

    public abstract UserDao userDao();

    /**
     * create db if it dose not exist and then return db
     *
     * @param context
     * @return an object of db
     */
    public static AppDatabase getAppDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "vitamin_database")
                    // allow queries on the main thread.
                    // Don't do this on a real app! See PersistenceBasicSample for an example.
                    .allowMainThreadQueries()
                    .build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }
}

یک میز. getAppDatabase.