Flutter数据库适配插件nitrite_hive_adapter的使用
Flutter数据库适配插件nitrite_hive_adapter的使用
Nitrite Hive adapter 使用 Hive 作为 Nitrite 数据库的文件存储引擎。
开始使用
要在你的项目中使用 Hive 作为 Nitrite 的存储引擎,请添加以下依赖:
dart pub add nitrite_hive_adapter
使用方法
要使用 Hive 作为存储引擎,你需要创建一个 HiveModule
并将其传递给 Nitrite 构建器。
// 创建一个基于 Hive 的存储模块
var storeModule = HiveModule.withConfig()
.crashRecovery(true)
.path('$dbDir/db')
.build();
// 初始化使用构建器
var db = await Nitrite.builder()
.loadModule(storeModule)
.openOrCreate(username: 'user', password: 'pass123');
示例代码
以下是一个完整的示例,展示了如何使用 nitrite_hive_adapter
插件来操作数据库。
import 'dart:io';
import 'dart:math';
import 'package:collection/collection.dart';
import 'package:faker/faker.dart';
import 'package:nitrite/nitrite.dart';
import 'package:nitrite_hive_adapter/nitrite_hive_adapter.dart';
part 'example.no2.dart';
void main() async {
// 创建一个 Nitrite 数据库
var db = await createDatabase();
// 执行集合操作
await collectionExample(db);
// 执行对象仓库操作
await objectRepositoryExample(db);
// 执行事务操作
await transactionExample(db);
// 关闭数据库
await db.close();
}
Future<Nitrite> createDatabase() async {
// 定义数据库路径
var dbPath = '${Directory.current.path}${Platform.pathSeparator}db'
'${Platform.pathSeparator}${faker.guid.guid()}';
// 如果目录不存在,则创建目录
var dbDir = await Directory(dbPath).create(recursive: true);
var storeModule =
HiveModule.withConfig().crashRecovery(true).path(dbDir.path).build();
var db = await Nitrite.builder()
.loadModule(storeModule)
.registerEntityConverter(MyBookConverter())
.registerEntityConverter(BookIdConverter())
.openOrCreate(username: 'user', password: 'password');
return db;
}
Future<void> collectionExample(Nitrite db) async {
// 获取一个 Nitrite 集合
var coll = await db.getCollection('test');
// 创建文档
var doc1 = createDocument("firstName", "fn1")
.put("lastName", "ln1")
.put("birthDay", DateTime.parse("2012-07-01T16:02:48.440Z"))
.put("data", [1, 2, 3])
.put("list", ["one", "two", "three"])
.put("body", "a quick brown fox jump over the lazy dog")
.put("books", [
createDocument("name", "Book ABCD")..put("tag", ["tag1", "tag2"]),
createDocument("name", "Book EFGH")..put("tag", ["tag3", "tag1"]),
createDocument("name", "No Tag")
]);
var doc2 = createDocument("firstName", "fn2")
.put("lastName", "ln2")
.put("birthDay", DateTime.parse("2010-06-12T16:02:48.440Z"))
.put("data", [3, 4, 3])
.put("list", ["three", "four", "five"])
.put("body", "quick hello world from nitrite")
.put("books", [
createDocument("name", "Book abcd")..put("tag", ["tag4", "tag5"]),
createDocument("name", "Book wxyz")..put("tag", ["tag3", "tag1"]),
createDocument("name", "No Tag 2")
]);
var doc3 = createDocument("firstName", "fn3")
.put("lastName", "ln2")
.put("birthDay", DateTime.parse("2014-04-17T16:02:48.440Z"))
.put("data", [9, 4, 8])
.put(
"body",
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nunc mi, '
'mattis ullamcorper dignissim vitae, condimentum non lorem.')
.put("books", [
createDocument("name", "Book Mnop")..put("tag", ["tag6", "tag2"]),
createDocument("name", "Book ghij")..put("tag", ["tag3", "tag7"]),
createDocument("name", "No Tag")
]);
// 插入一个文档
await coll.insert(doc1);
// 插入多个文档
await coll.insertMany([doc2, doc3]);
// 在 firstName 上创建索引
await coll.createIndex(['firstName']);
// 在 body 上创建全文索引
await coll.createIndex(['body'], indexOptions(IndexType.fullText));
// 在 book tags 上创建索引
await coll.createIndex(['books.tag'], indexOptions(IndexType.nonUnique));
// 查找所有文档
var cursor = coll.find(filter: where('firstName').eq('fn1'));
print('First document where firstName is fn1: ${await cursor.toList()}');
cursor = coll.find(filter: where('body').text('Lorem'));
print('Documents where body contains Lorem: ${await cursor.toList()}');
cursor = coll.find(filter: where('books.tag').eq('tag2'));
print('Documents where books.tag is tag2: ${await cursor.toList()}');
// 删除所有索引
await coll.dropAllIndices();
// 在 list, lastName 和 firstName 上创建复合索引
await coll.createIndex(['list', 'lastName', 'firstName']);
cursor = coll.find(
filter: and([
where('lastName').eq('ln2'),
where("firstName").notEq("fn1"),
where("list").eq("four"),
]),
);
print(
'Documents where lastName is ln2, firstName is not fn1 and list contains'
' four: ${await cursor.toList()}');
// 更新一个集合
await coll.update(
where('firstName').eq('fn1'),
createDocument('firstName', 'fn1-updated'),
updateOptions(insertIfAbsent: true),
);
// 查找所有 firstName 已更新的文档
cursor = coll.find(filter: where('firstName').eq('fn1-updated'));
print('Documents where firstName is fn1-updated: ${await cursor.toList()}');
// 移除
await coll.remove(where('firstName').eq('fn1-updated'));
cursor = coll.find(filter: where('firstName').eq('fn1-updated'));
print('Documents where firstName is fn1-updated: ${await cursor.toList()}');
// 清空集合
await coll.clear();
// 删除集合
await coll.drop();
}
Future<void> objectRepositoryExample(Nitrite db) async {
// 获取一个仓库
var repo = await db.getRepository<Book>();
// 创建一本书
var book = randomBook();
// 插入一本书
await repo.insert(book);
// 插入多本书
await repo.insertMany([randomBook(), randomBook(), randomBook()]);
// 查找所有书籍
var cursor = repo.find();
print('All books: ${await cursor.toList()}');
// 按标签查找书籍
cursor = repo.find(filter: where('tags').eq('tag2'));
print('Books where tags is tag2: ${await cursor.toList()}');
// 按描述查找书籍
cursor = repo.find(filter: where('description').text('lorem'));
print('Books where description contains lorem: ${await cursor.toList()}');
// 按价格和出版商查找书籍
cursor = repo.find(
filter: and([
where('price').gt(100),
where('publisher').eq('publisher1'),
]),
);
print('Books where price is greater than 100 and publisher is publisher1: '
'${await cursor.toList()}');
// 按书 ID 查找书籍
cursor = repo.find(
filter: where('book_id.isbn').eq(book.bookId!.isbn),
);
print('Books where bookId is ${book.bookId}: '
'${await cursor.toList()}');
// 更新一本书
await repo.updateDocument(
where('book_id').eq(book.bookId!),
createDocument('price', 100.0),
justOnce: false,
);
// 查找所有价格已更新的书籍
cursor = repo.find(filter: where('price').eq(100.0));
print('Books where price is 100: ${await cursor.toList()}');
// 移除
await repo.remove(where('price').eq(100.0));
cursor = repo.find(filter: where('price').eq(100.0));
print('Books where price is 100: ${await cursor.toList()}');
// 清空仓库
await repo.clear();
// 删除仓库
await repo.drop();
}
Future<void> transactionExample(Nitrite db) async {
// 获取一个仓库
var repo = await db.getRepository<Book>();
// 创建一本书
var book = randomBook();
var session = db.createSession();
var tx = await session.beginTransaction();
var txRepo = await tx.getRepository<Book>();
await txRepo.insert(book);
var txCursor = txRepo.find();
print('Books inserted in transaction: ${await txCursor.toList()}');
var cursor = repo.find();
print('Books in the original repository: ${await cursor.toList()}');
await tx.commit();
// 在事务中插入多本书
await session.executeTransaction((tx) async {
var txRepo = await tx.getRepository<Book>();
await txRepo.insertMany([randomBook(), randomBook(), randomBook()]);
var cursor = repo.find();
print('Books before committing 2nd transaction: ${await cursor.toList()}');
});
// 查找所有书籍
cursor = repo.find();
print('All books after transaction: ${await cursor.toList()}');
// 删除仓库
await repo.drop();
}
更多关于Flutter数据库适配插件nitrite_hive_adapter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复