Android Architecture Components 之 Room 篇

本文详细介绍了Android Architecture Components中的Room组件,包括如何定义Entity、使用DAO进行数据操作,以及数据库的更新与迁移。文章指出,每个Entity代表一张表,主键、索引和关系的设置对数据库性能至关重要。此外,DAO接口提供了插入、更新、删除和查询数据的方法,Room在编译时会验证SQL查询。最后,文章强调了数据库迁移的重要性,并展示了如何编写Migration来保护用户数据。
摘要由CSDN通过智能技术生成

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VNfFSo5n-1651804572351)(https://user-gold-cdn.xitu.io/2018/4/16/162cdce4ffd755e4?imageView2/0/w/1280/h/960/ignore-error/1)]

@Entity(tableName = “products”)
public class ProductEntity {

@PrimaryKey
private int id;
private String name;
private String description;

}

@Dao
public interface ProductDao {

@Query(“select * from products”)
List getAllProducts();

@Query(“select * from products where id = :id”)
ProductEntity findProductById(int id);

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertProduct(ProductEntity product);

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAllProducts(List products);

@Delete
void deleteProduct(ProductEntity product);
}

@Database(entities = {ProductEntity.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract ProductDao productDao();
}

AppDatabase appDatabase = Room.databaseBuilder(this, AppDatabase.class, “product.db”).build();
ProductDao productDao = appDatabase.productDao();

List allProducts = productDao.getAllProducts();

productDao.insertProduct(productEntity);

每个 entity 都代表了一张表,其中的字段代表表中的一列。注解处理 《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》无偿开源 徽信搜索公众号【编程进阶路】 器会自动生成 AppDatabaseProductDao 对应的实现类 AppDatabase_ImplProductDao_Impl。可以通过调用Room.databaseBuilder()Room.inMemoryDatabaseBuilder()在运行时获取Database实例,但要注意,实例化 RoomDatabase 是相当昂贵的,最好按照单例模式只创建一个Database实例。

定义 Entity

为了让 Room 可以访问 entity,entity 中的字段必须是 public 的,或者提供了getter/setter方法。默认情况下,Room 会将 entity 中的每个字段作为数据库表中一列,如果你不想持久化某个字段,可以使用 @Ignore 注解。默认数据库表名为 entity 类名,你可以通过 @Entity 注解的 tableName 属性 更改,默认列名是字段名,你可以通过 @ColumnInfo 注解更改。

主键

每个 entity 必须至少有一个字段作为主键(primary key),即使该 entity 只有一个字段。使用 @PrimaryKey 注解来指定主键,如果你希望 SQLite 帮你自动生成这个唯一主键,需要将 @PrimaryKeyautoGenerate 属性设置成 true,不过需要改列是 INTEGER 类型的。如果字段类型是 longintInsert 方法会将 0 作为缺省值,如果字段类型是 IntegerLong 类型,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值