module 下build.gradle 配置 schemas
defaultConfig { javaCompileOptions { annotationProcessorOptions { arguments = ["room.schemaLocation": "$projectDir/schemas".toString()] } } }
1. 实体@Entity 映射到表
@Entity(tableName = "users")
public class User {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "user_id")
private int userId;
@ColumnInfo(name = "user_name")
private String name;
@ColumnInfo(name = "user_address",defaultValue = "四川省成都市")
private String address;
@ColumnInfo(name = "user_age")
private int age;
public User(int userId, String name, String address, int age) {
this.userId = userId;
this.name = name;
this.address = address;
this.age = age;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", name='" + name + '\'' +
", address='" + address + '\'' +
", age=" + age +
'}';
}
}
2. Dao
@Dao
public interface UserDao {
@Query("select * from users")
List<User> getAllUsers();
@Query("select * from users where user_id = :id")
User getUserById(int id);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertUser(User userModel);
@Query("update users set user_name = :name AND user_age = :age WHERE user_id = :id")
void updateUser(int id, String name, String age);
@Update(onConflict = OnConflictStrategy.REPLACE)
void updateUsers(User... users);
@Query("delete from users where user_id = :id")
void deleteUserById(int id);
@Delete
void deleteUsers(User... users);
}
3. DataBase
@Database(entities = {User.class, Student.class}, version = 1)
public abstract class UserDataBase extends RoomDatabase {
private static UserDataBase instance;
private static final String DB_NAME = "mydata.db";
public static UserDataBase getInstance(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context.getApplicationContext(),UserDataBase.class, DB_NAME)
.allowMainThreadQueries()
.build();
}
return instance;
}
public abstract UserDao userDao();
public abstract StudentDao studentDao();
}
4. 使用
UserDao userDao = UserDataBase.getInstance(MainActivity.this).userDao();
userDao.insertUser(new User("gali"+i,"四川成都"+i,2*i,"男"));
List<User> data = userDao.getAllUsers();
5.如果更新表 User新加一个字段
@Entity(tableName = "users")
public class User {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "user_id")
private int userId;
@ColumnInfo(name = "user_name")
private String name;
@ColumnInfo(name = "user_address",defaultValue = "四川省成都市")
private String address;
@ColumnInfo(name = "user_age")
private int age;
@ColumnInfo(name = "user_sex")
private String sex;
public User( String name, String address, int age,String sex) {
this.name = name;
this.address = address;
this.age = age;
this.sex = sex;
}
}
@Database(entities = {User.class, Student.class}, version = 2)
public abstract class UserDataBase extends RoomDatabase {
private static UserDataBase instance;
private static final String DB_NAME = "mydata.db";
public static UserDataBase getInstance(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context.getApplicationContext(),UserDataBase.class, DB_NAME)
.addMigrations(MIGRATION_1_2)
.allowMainThreadQueries()
.build();
}
return instance;
}
public static Migration MIGRATION_1_2 = new Migration(1,2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("alter table users add column user_sex text");
}
};
public abstract UserDao userDao();
public abstract StudentDao studentDao();
}
6. 如果再新加一个表
@Entity(tableName = "persons")
public class Person {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "person_id")
int personId;
@ColumnInfo(name = "person_name")
String name;
public Person(String name) {
this.name = name;
}
}
@Dao
public interface PersonDao {
@Query("select * from persons")
List<Person> getAllPerson();
@Query("select * from persons where person_id = :id")
Person getPersonById(int id);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertPerson(Person userModel);
}
@Database(entities = {User.class, Student.class,Person.class}, version = 3) public abstract class UserDataBase extends RoomDatabase { private static UserDataBase instance; private static final String DB_NAME = "mydata.db"; public static UserDataBase getInstance(Context context) { if (instance == null) { instance = Room.databaseBuilder(context.getApplicationContext(),UserDataBase.class, DB_NAME) .addMigrations(MIGRATION_1_2) .addMigrations(MIGRATION_2_3) .allowMainThreadQueries() .build(); } return instance; } public static Migration MIGRATION_1_2 = new Migration(1,2) { @Override public void migrate(@NonNull SupportSQLiteDatabase database) { database.execSQL("alter table users add column user_sex text"); } }; public static Migration MIGRATION_2_3 = new Migration(2,3) { @Override public void migrate(@NonNull SupportSQLiteDatabase database) { database.execSQL("create table persons(person_id INTEGER primary key autoincrement not null,person_name TEXT ) "); } }; public abstract UserDao userDao(); public abstract StudentDao studentDao(); public abstract PersonDao personDao(); }