Room数据库框架的使用

2024-04-03 13:48
文章标签 使用 数据库 框架 room

本文主要是介绍Room数据库框架的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

google推出了自己的数据库框架:Room  有点类似于greenDao的使用

官方介绍:The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite

1、首先我们需要在项目的build.gradlle文件添加google的maven仓库

allprojects {repositories {google()jcenter()}
}

2、接着在主module的build.gradle文件添加依赖

implementation 'android.arch.persistence.room:runtime:1.1.1'
annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
implementation 'android.arch.persistence.room:testing:1.1.1'

3、接下来建立一个实体类,类似于greendao,都i是通过实体类映射的方式来创建

@Entity(tableName = "article_type")
public class ArticleType {//设置主键,并且定义自增增@PrimaryKey(autoGenerate = true)private int id;//字段映射具体的数据表字段名@ColumnInfo(name = "name")private String name;@ColumnInfo(name = "count")private int count;@ColumnInfo(name = "title")private String title;@ColumnInfo(name = "image")private String image;@ColumnInfo(name = "content")private String content;@Overridepublic String toString() {return "ArticleType{" +"id=" + id +", name='" + name + '\'' +", count=" + count +", title='" + title + '\'' +", image='" + image + '\'' +", content='" + content + '\'' +'}';}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 int getCount() {return count;}public void setCount(int count) {this.count = count;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getImage() {return image;}public void setImage(String image) {this.image = image;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}

//必须指定一个构造方法,room框架需要。并且只能指定一个

//,如果有其他构造方法,则其他的构造方法必须添加@Ignore注解

 public ArticleType() { }//其他构造方法要添加@Ignore注解@Ignorepublic ArticleType(int id, String name, int count, String title, String image, String content) {this.id = id;this.name = name;this.count = count;this.title = title;this.image = image;this.content = content;}
}

注意:(1)@Entity(tableName="表名称")    此注解放在实体类的类名上面,可以设置表的名称、主键、外键等信息

           (2)@PrimaryKey(autoGenerate = true)  此注解放在主键变量上,并定义自增

           (3)@ColumnInfo(name = "字段名称")  此注解放在普通变量上,字段映射具体的数据表字段名

           (4)@Ignore        这个注解需要好好说一下,放在方法和变量上。Room定义必须有一个无参的构造方法,所以说如果你想有别的构造方法,需要在别的构造方法上添加上此注解。如果说你实体类中的字段不是表中的字段,这时也需要忽略下,需要在变量上添加此注解

 

4、增删改查

(1)、增加 @Insert(onConflict = OnConflictStrategy.REPLACE)
OnConflictStrategy.REPLACE表如已有数据,就覆盖掉。数据的判断通过主键进行匹配,也就是id,非整个ArticleType对象。增加分为两种,一种是增加一条、另外一种是增加多条数据,

@Insert(onConflict = OnConflictStrategy.REPLACE)
Long insert(ArticleType articleType);@Insert(onConflict = OnConflictStrategy.REPLACE)
List<Long> insertAll(List<ArticleType> articleTypeList);

(2)、删除

@Delete()
int delete(ArticleType articleType);@Delete()
int deleteAll(List<ArticleType> articleTypeList);

(3)、修改     需要传入修改完的实体类,其中必须要有主键(通过主键来进行修改)

@Update()
int update(ArticleType articleType);@Update()
int updateAll(ArticleType...articleTypes);

(4)、查询

查询 @Query("SELECT * FROM  article_type")
查询灵活性就很大了,可以直接里面写sql语句。很赞的是:Room可以直接判断你写的表名是否存在,还和参数值一一对应。

@Query("SELECT * FROM article_type")
List<ArticleType> getAll();@Query("SELECT * FROM article_type WHERE id = :memberId")
LiveData<ArticleType> findById(int memberId);

5、数据库创建

表的实体类在上面已经写完,接下来创建一下数据库。需要继承自RoomDatabase。

@Database(entities = {ArticleType.class,FamilyMemberType.class}, version = 1,exportSchema = true)
public abstract class AppDataBase extends RoomDatabase {public abstract ArticleTypeDao articleTypeDao();public abstract FamilyMemberType familyMemberTypeDao();public static final Migration MIGRATION_1_2 = new Migration(1, 2) {@Overridepublic void migrate(@NonNull SupportSQLiteDatabase database) {database.execSQL("ALTER TABLE article_type ADD COLUMN age INTEGER NOT NULL DEFAULT 0");}};
}

需要在创建的类的上面添加@Database注解,其中的entities是一个数组,可以添加多个类,相应的在下面可以创建多个抽象方法(多个表的情况下),以便使用。下面就是创建数据库

private AppDataBase db=null;
private ArticleTypeDao dao=null;
db = Room.databaseBuilder(this, AppDataBase.class, "room-database").build();
dao = db.articleTypeDao();
下面以查询为例:记得操作数据库,需要开启子线程
long result = dao.insert(new ArticleType(1, "李伟", 80, "今天搞活动", "http://www.image.com", "下班"));
if (result > 0) {i++;Log.i("insert_data_success", "插入了一条数据成功");
} else {Log.i("insert_data_success", "插入失败、、、");
}

参考:原文链接:https://blog.csdn.net/haojiagou/article/details/103053792

这篇关于Room数据库框架的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/873089

相关文章

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

SQL Server数据库死锁处理超详细攻略

《SQLServer数据库死锁处理超详细攻略》SQLServer作为主流数据库管理系统,在高并发场景下可能面临死锁问题,影响系统性能和稳定性,这篇文章主要给大家介绍了关于SQLServer数据库死... 目录一、引言二、查询 Sqlserver 中造成死锁的 SPID三、用内置函数查询执行信息1. sp_w