react native学习笔记18——存储篇(3)Realm
来源:互联网 发布:钢结构荷载计算软件 编辑:程序博客网 时间:2024/06/11 18:57
前言
Realm是一款新兴的针对移动平台设计的数据库,使用简单、跨平台、性能优越功能强大。其官网地址为:https://realm.io/。Realm与sqlite在性能上各有优势,但其更加简单易用,学习成本低。
配置
1. 安装
在项目的根目录下执行cmd命令:
npm install --save realm
2. 将项目关联realm原生模块库
react-native link realm
注意:在Android中,
react-native link
可能产生无效配置,例如成功更新了Gradle的配置(android/settings.gradle
和android/app/build.gradle
),但没有添加Realm模块。首先确认是否成功添加Realm模块,如果没有,需要手动添加,步骤如下:
1.修改android/settings.gradle配置
...include ':realm'project(':realm').projectDir = new File(rootProject.projectDir, '../node_modules/realm/android')
2.修改android/app/build.gradle的配置
...dependencies { ... compile project(':realm')}
3.在MainApplication.java注册模块
修改android/app/src/main/java/com/[YourAppName]/MainApplication.java的配置
import io.realm.react.RealmReactPackage; // add this importpublic class MainApplication extends Application implements ReactApplication { @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new RealmReactPackage() // add this line ); }}
使用实例
下例是官网的一个最基础的实例:
import React, { Component } from 'react';import { AppRegistry, Text, View, StyleSheet,} from 'react-native';const Realm = require('realm');const DogSchema = { name: 'Dog', primaryKey:'id', properties: { id:'int', dogname:'string', color:'string', }};export default class RealmDemo extends Component { constructor(props) { super(props); this.state = { realm: null }; } componentWillMount() { let realm = new Realm({schema: [DogSchema]}); realm.write(() => { realm.create('Dog', {id:0,dogname: 'Rex', color:'red'}); realm.create('Dog', {id:1,dogname: 'Jeff', color:'green'}); realm.create('Dog', {id:2,dogname: 'Dave', color:'black'}); //更新id为1的数据 realm.create('Dog', {id:1, color:'white'},true); }); this.setState({realm}); } render() { const info = this.state.realm ? 'Number of dogs in this Realm: ' + this.state.realm.objects('Dog').length : 'Loading...'; return ( <View style={styles.container}> <Text > {info} </Text> </View> );}}const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f2f2f2', paddingTop:20, },});
新建表模型
在进行数据库的增删改查之前,首先得创建数据库表。
该实例中用Realm新建一个名为Dog
的表。表模型的设计如下:
//新建表模型const DogSchema = { name: 'Dog', primaryKey:'id', properties: { id:'int', dogname:'string', color:'string', }};
- name: 表名字。
- primaryKey: 主键,可以是 ‘int’ 或’string’,主键必须保持唯一性,一旦将某字段设定为主键后该表的主键无法变更。
- properties: 该属性内设置自定义的表字段名。如上例中
properties: {dogname: 'string'}
中dogname
为字段名,string
为类型。
建表
//建表let realm = new Realm({schema: [DogSchema]});
也可同时创建多个表,如:
let realm = new Realm({schema: [DogSchema,CatSchema,PersonSchema]});
Realm支持以下的一些基础类型:bool,int,float,double,string,data和date。
- bool属性映射到JavaScript中Boolean对象
- int,float和double属性映射到JavaScript中Number对象,不过’int’和’double’会以64位进行存储但是float会以32位进行存储
- string属性会被映射成String对象
- data属性会被映射成ArrayBuffer对象
- date属性会被映射成Date对象
当需要对属性进行设置类型的时候,一般直接写属性类型就行,不需要使用一个字典格式的写法,虽然下面两种写法是等价的。
const DogSchema = { name: 'Car', properties: { // The following property types are equivalent dogname: {type: 'string'}, color: 'string', }}
插入数据
realm.write(() => { realm.create('Dog', {id:0,dogname: 'Rex', color:'red'}); realm.create('Dog', {id:1,dogname: 'Jeff', color:'green'}); realm.create('Dog', {id:2,dogname: 'Dave', color:'black'});});
查询数据
- 查询所有数据
可通过realm.objects(“name”)的方式获取该数据表所有的数据。
let dogs = realm.objects('Dog');console.log ('name:' + dogs[0].dogname);
- 根据条件查询数据
可通过filtered方法对查询到的所有数据进行筛选,如下:
let dogs = realm.objects('Dog'); let redDogs = dogs.filtered('color = "red" AND name BEGINSWITH "B"');
当前Realm仅支持部分NSPredicate语法进行查询语句的筛选:对数字类型的数据支持基本的比较操作:==
,!=
, >
,>=
, <
, 和 <=
。对string类型支持:==
, BEGINSWITH
, ENDSWITH
, CONTAINS
。string类型数据可以不分大小写通过==[c]
,BEGINSWITH[c]
等等比较过滤。同样比较的时候可以通过获取对象的属性获取数据进行比较例如car.color=='blue'
。
目前的Realm版本(Realm Javascript 2.0.4)仅支持Realm类型数据的列表的筛选,以后可能会支持基本类型数据的列表筛选。
更新数据
如果构建的表模型中含有主键primaryKey,可以利用realm.create方法根据primaryKey修改对应的数据的值,并在第三个参数传入true。
realm.create('Dog', {id:1, color:'white'},true);
在上例中由于我们已经存在了id为1的数据,并且第三个参数传入了true,因此color属性会被更新为white值而不是新增一条数据。
删除数据
realm.write(() => { // Create a dog object let dog = realm.create('Dog', {id:0,dogname: 'Rex', color:'red'}); //删除单个数据 // Delete the dog realm.delete(dog); //删除所有数据 // Delete multiple dogs by passing in a `Results`, `List` or JavaScript `Array` let allDogs = realm.objects('Dog'); realm.delete(allDogs); // Deletes all dogs});
自动更新的特性
查询Realm返回的列表对象,对列表数据更新会自动保存在底层Realm中,这也意味着我们没有必要去重新查询数据库获取数据,修改列表对象会立即影响到查询的结果。
let night = realm.objects('Dog').filtered('dogname = "Night"');// night.length == 0realm.write(() => { realm.create('Dog', {id:3,dogname: 'Night', color:'red'});});// night.length == 1
上例中首先查询dogname为Night的狗,返回结果为0(因为我们根本就没添加),然后插入一条dogname为Night的数据,而此时并没有重新查询该表,但查询结果中已经有了一条数据了。
以上是realm的基本数据操作方法,如需更深入的了解,可以查看官方文档
- react native学习笔记18——存储篇(3)Realm
- React Native Realm数据库存储
- react native学习笔记16——存储篇(1)AsyncStorage
- react native学习笔记17——存储篇(2)SQLite
- React Native学习笔记(3)--FlexBox
- react native学习笔记5——布局实战篇
- React-Native Realm使用
- react-native 填坑之旅 数据库存储 realm
- Shiro 学习笔记(3)—— 自定义 Realm
- react native学习笔记21——常用API(3)Geolocation定位、Keyboard键盘
- React-Native 学习笔记
- react native学习笔记
- react-native 学习笔记
- 学习笔记 - React Native
- React Native 学习笔记
- React Native 学习笔记
- react-native 学习笔记
- React Native学习笔记
- 11g dg 从库sql性能问题处理吐槽
- 两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同
- 关于web.xml里面使用classpath:找不到文件
- java poi实现execl三级联动
- java.lang.IllegalStateException: The specified child already has a parent. You must call removeView(
- react native学习笔记18——存储篇(3)Realm
- xtrabackup恢复备份后,mysql无法启动,报Job failed to start
- lightdm-login-chromeos, 将 chromiumos vibe窗口管理器安装到 Ubuntu
- at91sam9260的Telnet远程登录开发板
- python DataFrame 取差集
- Spring Security 默认的过滤器链
- eclipse上tomcat运行动态网页404的解决方法(并不完美但有效)
- CocosCreator PageView组件使用
- js:继承