直接贴
def room_version ="2.2.5"
compile"android.arch.persistence.room:runtime:1.1.1"
annotationProcessor"android.arch.persistence.room:compiler:1.1.1"
----------------
新建三个类一个包下
@Dao
public interface UserDao {
@Query("SELECT * FROM user")
ListgetAll();
@Query("SELECT * FROM user WHERE uid IN (:userIds)")
ListloadAllByIds(int[] userIds);
@Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
"last_name LIKE :last LIMIT 1")
UserfindByName(String first, String last);
@Insert
void insertAll(User... users);
@Delete
void delete(User user);
}
----------------------------
@Entity(tableName ="user")
public class User {
@PrimaryKey
public int uid;
@ColumnInfo(name ="first_name")
public StringfirstName;
@ColumnInfo(name ="last_name")
public StringlastName;
public User(int uid) {
this.uid = uid;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public StringgetFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public StringgetLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
----------------
@Database(entities = {User.class}, version =1)
public abstract class AppDatabaseextends RoomDatabase {
public abstract UserDaouserDao();
}
不要忘了 application中
private static final ObjectsLock =new Object();
private static AppDatabaseINSTANCE;
public static AppDatabasegetInstance(Context context) {
synchronized (sLock) {
if (INSTANCE ==null) {
INSTANCE =
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "user.db")
.build();
}
return INSTANCE;
}
}