android Room使用

使用Room实现数据库增删改查。

  1. 引入room
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
  1. 添加配置
android {
	defaultConfig {
		javaCompileOptions {
            annotationProcessorOptions {
                arguments = [  
                	// app内会自动生产schemas文件夹
					"room.schemaLocation":"$projectDir/schemas".toString()
                ]
            }
        }
	}
}

3.创建实体类

@Entity(tableName = "device") // 表名
public class DeviceEntity {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    private int id;
    private String name;
    private String code;

    public DeviceEntity() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}

4.创建Dao文件

@Dao
public interface DeviceDao {
	
	// 查全部
    @Query("SELECT * FROM device")
    List<DeviceEntity> getAll();

	// 模糊查询
    @Query("SELECT * FROM device WHERE name LIKE '%' || :keyword || '%' OR code LIKE '%' || :keyword || '%'")
    List<DeviceEntity> getAll(String keyword);

	// 查询是否存在
    @Query("SELECT EXISTS (SELECT 1 FROM device WHERE code = :code OR name = :name)")
    boolean isExistDevice(String code, String name);
	
	// 插入
    @Insert
    void insert(DeviceEntity device);

	// 修改
    @Update
    int updateDevice(DeviceEntity device);

	// 删除
    @Query("DELETE FROM device where id=:id")
    void delete(int id);
}

5.创建Database

@Database(entities = {DeviceEntity.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract DeviceDao deviceDao();

    private static volatile AppDatabase INSTANCE;

    public static AppDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            AppDatabase.class, "my_db") // 数据库名称
                            .allowMainThreadQueries()
                            .build();
                }
            }
        }
        return INSTANCE;
    }
}

6.使用

DeviceDao deviceDao = AppDatabase.getDatabase(this).deviceDao();
deviceDao.getAll();

7.版本升级
修改实体类中的字段后,修改AppDatabase文件

@Database(entities = {DeviceEntity.class}, version = 2)
public abstract class AppDatabase extends RoomDatabase {
    public abstract DeviceDao deviceDao();

    private static volatile AppDatabase INSTANCE;

 	//添加版本号1到2的处理
    private static Migration MIGRATION_1_2 = new Migration(1,2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE device " + " ADD COLUMN signal TEXT "); // 添加字段
        }
    };

    public static AppDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            AppDatabase.class, "my_db") // 数据库名称
                            .allowMainThreadQueries()
                            .addMigrations(MIGRATION_1_2) // 添加
                            .build();
                }
            }
        }
        return INSTANCE;
    }
}
  1. 通过Index的unique设置一个或多个字段唯一性。
    实体类添加indices
@Entity(tableName = "device" , indices = {@Index(value = {"name", "code"}, unique = true)}) 

如果涉及到数据升级,需要执行


private static Migration MIGRATION_1_2 = new Migration(1,2) {
    @Override
    public void migrate(@NonNull SupportSQLiteDatabase database) {
        CREATE UNIQUE INDEX index_device_name_code ON device(name, code);
    }
};

你可能感兴趣的:(Android,android,开发语言)