【鸿蒙实战】从 Preferences 到关系型数据库: 构建可靠的仓储订单管理模块【鸿蒙心迹】
【鸿蒙实战】从 Preferences 到关系型数据库:构建可靠的仓储订单管理模块【鸿蒙心迹】
一、项目背景:从一个简单的存储需求开始
假设我们正在开发一套企业仓储管理应用,仓库管理员可以通过鸿蒙平板完成商品管理、库存查询、订单创建和商品出库。
随着业务逐渐完善,系统需要管理的数据越来越多:
- 商品基本信息
- 商品分类和价格
- 仓库库存
- 商品预留库存
- 出库订单
- 订单商品明细
- 订单处理状态
最初,我们可能只需要保存用户上次选择的仓库编号,于是使用 Preferences 就能解决问题。
但是当业务发展到订单管理时,问题就出现了。
一张订单可能包含多个商品,一个商品也可能出现在不同订单中。订单创建、明细保存和库存扣减之间存在明确的业务关联。
如果继续把这些数据简单地保存成 Key-Value,就会逐渐增加数据组织、查询和维护的复杂度。
因此,这次我们以一个完整的仓储订单管理模块为背景,从 Preferences 过渡到 RelationalStore,完成一套更符合企业级开发需求的数据管理方案。
二、整体架构设计
先明确整个模块的技术架构。
ArkUI 页面层
|
商品管理 / 订单管理
|
v
Service 层
|
-----------------------
| | |
Product Inventory Outbound
Service Service Service
| | |
-----------------------
|
v
Repository 层
|
-----------------------
| |
Preferences RelationalStore
用户配置 业务结构化数据
|
v
SQLite
这里有一个设计原则:
不同类型的数据应该使用适合它的数据存储方案,而不是所有数据都塞进同一种存储方式。
1. Preferences 负责什么?
Preferences 主要保存:
- 最近选择的仓库编号
- 商品列表默认筛选条件
- 用户界面主题
- 每页显示数量
- 用户个性化配置
这些数据具有轻量级、Key-Value 的特点。
2. RelationalStore 负责什么?
RelationalStore 负责:
- 商品信息
- 库存记录
- 出库订单
- 订单商品明细
- 商品与订单之间的关联关系
这些数据需要结构化查询、条件更新、关联管理和事务保障。
三、Preferences 和 RelationalStore 的区别
| 对比维度 | Preferences | RelationalStore |
|---|---|---|
| 数据模型 | Key-Value | 关系型数据 |
| 典型用途 | 用户配置 | 订单、库存 |
| 数据查询 | 按 Key 读取 | SQL 条件查询 |
| 关联关系 | 不提供关系模型 | 支持关系结构 |
| 事务能力 | 不提供关系型数据库事务 | 支持数据库事务 |
| 索引 | 不提供 SQL 索引 | 支持索引 |
| 适用规模 | 轻量级数据 | 结构化业务数据 |
Preferences 默认使用 XML 存储模式,数据操作主要发生在内存中,需要时通过 flush 持久化;API 18 起还提供 GSKV 模式,支持多进程并发读写。
因此,不能简单地认为 Preferences 不能存业务数据,而应该根据业务数据结构、访问方式、并发要求和数据规模选择。
四、数据库表设计
一个仓储订单模块至少需要四张核心数据表。
1. products:商品表
保存商品基础信息。
CREATE TABLE IF NOT EXISTS products (
product_id TEXT PRIMARY KEY,
sku TEXT NOT NULL UNIQUE,
product_name TEXT NOT NULL,
category TEXT NOT NULL,
unit_price_cents INTEGER NOT NULL
CHECK(unit_price_cents >= 0),
status TEXT NOT NULL DEFAULT 'ACTIVE',
create_time INTEGER NOT NULL
);
这里价格使用整数分存储,而不是直接使用浮点数。
例如:
189.00 元保存为 18900。
这样可以避免浮点数运算带来的金额精度问题。
2. inventory:库存表
CREATE TABLE IF NOT EXISTS inventory (
warehouse_code TEXT NOT NULL,
product_id TEXT NOT NULL,
on_hand_qty INTEGER NOT NULL DEFAULT 0
CHECK(on_hand_qty >= 0),
reserved_qty INTEGER NOT NULL DEFAULT 0
CHECK(
reserved_qty >= 0
AND reserved_qty <= on_hand_qty
),
update_time INTEGER NOT NULL,
PRIMARY KEY (warehouse_code, product_id),
FOREIGN KEY (product_id)
REFERENCES products(product_id)
);
这里需要区分两个概念:
- on_hand_qty:实际在库数量。
- reserved_qty:已经被订单预留的数量。
可用库存:
available_qty = on_hand_qty - reserved_qty
例如:
实际库存 120 件,已经预留 15 件,那么可用库存就是 105 件。
3. orders:订单主表
CREATE TABLE IF NOT EXISTS orders (
order_no TEXT PRIMARY KEY,
request_id TEXT NOT NULL UNIQUE,
warehouse_code TEXT NOT NULL,
customer_name TEXT NOT NULL,
status TEXT NOT NULL,
total_amount_cents INTEGER NOT NULL,
create_time INTEGER NOT NULL
);
这里有两个关键字段:
- order_no:业务订单号。
- request_id:幂等请求编号。
订单号用于识别订单,request_id 用于防止相同业务请求被重复处理。
4. order_items:订单明细表
CREATE TABLE IF NOT EXISTS order_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
order_no TEXT NOT NULL,
product_id TEXT NOT NULL,
quantity INTEGER NOT NULL CHECK(quantity > 0),
unit_price_cents INTEGER NOT NULL,
line_amount_cents INTEGER NOT NULL,
create_time INTEGER NOT NULL,
FOREIGN KEY (order_no)
REFERENCES orders(order_no),
FOREIGN KEY (product_id)
REFERENCES products(product_id)
);
为什么订单明细中还要保存商品价格?
因为商品价格可能发生变化。
如果只保存 product_id,未来查询历史订单时,直接关联商品表获取价格,就可能得到商品最新价格,而不是订单创建时的成交价格。
因此订单明细需要保存当时的价格快照。
5. 四张表之间的关系
products
|
1 | 1
\ | /
\ | /
inventory
products 1 -------- N order_items
orders 1 -------- N order_items
其中:
- 一个商品可以有多条不同仓库的库存记录。
- 一个订单可以有多条订单明细。
- 一条订单明细对应一个商品。
数据库创建时开启外键约束:
PRAGMA foreign_keys = ON;
注意应在开启事务之前执行,并在实际目标环境验证外键约束是否按预期生效。
五、初始化 RelationalStore
首先导入模块:
import { relationalStore } from '@kit.ArkData';
import { common } from '@kit.AbilityKit';
创建数据库管理类:
文件:WarehouseDatabase.ets
import { relationalStore } from '@kit.ArkData';
import { common } from '@kit.AbilityKit';
export class WarehouseDatabase {
private static store:
relationalStore.RdbStore | undefined = undefined;
static async init(
context: common.UIAbilityContext
): Promise<void> {
const config: relationalStore.StoreConfig = {
name: 'warehouse.db',
securityLevel: relationalStore.SecurityLevel.S3
};
const store = await relationalStore.getRdbStore(
context,
config
);
// 开启外键约束
await store.executeSql('PRAGMA foreign_keys = ON');
let version = store.version;
// 第一版:创建核心数据表
if (version < 1) {
await this.runMigration(store, [
`CREATE TABLE IF NOT EXISTS products (
product_id TEXT PRIMARY KEY,
sku TEXT NOT NULL UNIQUE,
product_name TEXT NOT NULL,
category TEXT NOT NULL,
unit_price_cents INTEGER NOT NULL
CHECK(unit_price_cents >= 0),
status TEXT NOT NULL DEFAULT 'ACTIVE',
create_time INTEGER NOT NULL
)`,
`CREATE TABLE IF NOT EXISTS inventory (
warehouse_code TEXT NOT NULL,
product_id TEXT NOT NULL,
on_hand_qty INTEGER NOT NULL DEFAULT 0
CHECK(on_hand_qty >= 0),
reserved_qty INTEGER NOT NULL DEFAULT 0
CHECK(
reserved_qty >= 0
AND reserved_qty <= on_hand_qty
),
update_time INTEGER NOT NULL,
PRIMARY KEY (warehouse_code, product_id),
FOREIGN KEY (product_id)
REFERENCES products(product_id)
)`,
`CREATE TABLE IF NOT EXISTS orders (
order_no TEXT PRIMARY KEY,
request_id TEXT NOT NULL UNIQUE,
warehouse_code TEXT NOT NULL,
customer_name TEXT NOT NULL,
status TEXT NOT NULL,
total_amount_cents INTEGER NOT NULL,
create_time INTEGER NOT NULL
)`,
`CREATE TABLE IF NOT EXISTS order_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
order_no TEXT NOT NULL,
product_id TEXT NOT NULL,
quantity INTEGER NOT NULL CHECK(quantity > 0),
unit_price_cents INTEGER NOT NULL,
line_amount_cents INTEGER NOT NULL,
create_time INTEGER NOT NULL,
FOREIGN KEY (order_no)
REFERENCES orders(order_no),
FOREIGN KEY (product_id)
REFERENCES products(product_id)
)`
]);
store.version = 1;
version = 1;
}
// 第二版:增加查询索引
if (version < 2) {
await this.runMigration(store, [
`CREATE INDEX IF NOT EXISTS idx_orders_status_time
ON orders(status, create_time)`,
`CREATE INDEX IF NOT EXISTS idx_items_order
ON order_items(order_no)`,
`CREATE INDEX IF NOT EXISTS idx_inventory_product
ON inventory(product_id)`
]);
store.version = 2;
}
this.store = store;
}
private static async runMigration(
store: relationalStore.RdbStore,
statements: string[]
): Promise<void> {
const transaction = await store.createTransaction();
try {
for (const sql of statements) {
await transaction.execute(sql);
}
await transaction.commit();
} catch (error) {
try {
await transaction.rollback();
} catch (rollbackError) {
console.error(
`Migration rollback failed: ${JSON.stringify(rollbackError)}`
);
}
throw error;
}
}
static getStore(): relationalStore.RdbStore {
if (this.store === undefined) {
throw new Error('数据库尚未初始化');
}
return this.store;
}
}
这里有几个重要设计。
第一,数据库只初始化一次。
不要在每次页面打开时重新创建数据库。
第二,使用数据库版本管理。
store.version 可以保存数据库版本。
当数据库表结构发生变化时,通过版本号执行增量迁移。
第三,迁移操作使用事务。
如果一组表结构变更中途失败,执行回滚,不应该把数据库版本提前升级。
第四,索引按实际查询场景设计。
不是所有字段都需要索引,索引过多也会增加写入和维护成本。
六、Preferences 实际使用
数据库负责业务数据,Preferences 负责用户配置。
例如保存用户上次选择的仓库。
文件:WarehouseSettings.ets
import { preferences } from '@kit.ArkData';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export class WarehouseSettings {
static saveLastWarehouse(
context: common.UIAbilityContext,
warehouseCode: string
): void {
const options: preferences.Options = {
name: 'warehouse_settings'
};
const prefs = preferences.getPreferencesSync(
context,
options
);
prefs.putSync('lastWarehouseCode', warehouseCode);
prefs.flush((error: BusinessError) => {
if (error) {
console.error(
`Preferences flush failed: ${error.code}`
);
return;
}
console.info('仓库配置保存成功');
});
}
static getLastWarehouse(
context: common.UIAbilityContext
): string {
const prefs = preferences.getPreferencesSync(
context,
{
name: 'warehouse_settings'
}
);
return prefs.getSync(
'lastWarehouseCode',
'WH-SH-01'
) as string;
}
}
这样就实现了两种存储方案的分工。
例如:
用户选择仓库 WH-SH-01
|
v
Preferences
|
v
保存最近使用的仓库编号
商品、库存、订单
|
v
RelationalStore
|
v
SQLite
不要把用户密码、访问令牌等敏感信息直接明文存入 Preferences。官方文档明确说明 Preferences 不支持通过配置直接进行数据加密存储。
七、商品管理:实现新增与查询
接下来开始实现业务。
定义商品模型:
export interface ProductInput {
productId: string;
sku: string;
productName: string;
category: string;
unitPriceCents: number;
warehouseCode: string;
initialStock: number;
}
export interface ProductInventory {
productId: string;
sku: string;
productName: string;
category: string;
unitPriceCents: number;
onHandQty: number;
reservedQty: number;
availableQty: number;
}
1. 新增商品
新增商品时,需要同时创建商品记录和对应仓库的库存记录。
import { WarehouseDatabase } from './WarehouseDatabase';
export class ProductService {
static async createProduct(
input: ProductInput
): Promise<void> {
if (
!input.productId ||
!input.sku ||
!input.productName ||
!Number.isInteger(input.unitPriceCents) ||
input.unitPriceCents < 0 ||
!Number.isInteger(input.initialStock) ||
input.initialStock < 0
) {
throw new Error('商品参数不合法');
}
const store = WarehouseDatabase.getStore();
const transaction = await store.createTransaction();
try {
const now = Date.now();
await transaction.insert('products', {
product_id: input.productId,
sku: input.sku,
product_name: input.productName,
category: input.category,
unit_price_cents: input.unitPriceCents,
status: 'ACTIVE',
create_time: now
});
await transaction.insert('inventory', {
warehouse_code: input.warehouseCode,
product_id: input.productId,
on_hand_qty: input.initialStock,
reserved_qty: 0,
update_time: now
});
await transaction.commit();
} catch (error) {
try {
await transaction.rollback();
} catch (rollbackError) {
console.error(
`Rollback failed: ${JSON.stringify(rollbackError)}`
);
}
throw error;
}
}
}
为什么这里也使用事务?
因为新增商品和创建库存记录属于同一个业务动作。
如果商品记录创建成功,但库存记录创建失败,就会出现商品已经存在,却没有对应仓库库存记录的问题。
所以两个操作应该一起成功或者一起失败。
2. 查询商品和库存
static async listProducts(
warehouseCode: string
): Promise<ProductInventory[]> {
const store = WarehouseDatabase.getStore();
const resultSet = await store.querySql(
`SELECT
p.product_id,
p.sku,
p.product_name,
p.category,
p.unit_price_cents,
COALESCE(i.on_hand_qty, 0) AS on_hand_qty,
COALESCE(i.reserved_qty, 0) AS reserved_qty,
COALESCE(
i.on_hand_qty - i.reserved_qty, 0
) AS available_qty
FROM products p
LEFT JOIN inventory i
ON p.product_id = i.product_id
AND i.warehouse_code = ?
WHERE p.status = ?
ORDER BY p.product_name ASC`,
[warehouseCode, 'ACTIVE']
);
const products: ProductInventory[] = [];
try {
while (resultSet.goToNextRow()) {
products.push({
productId: resultSet.getString(
resultSet.getColumnIndex('product_id')
),
sku: resultSet.getString(
resultSet.getColumnIndex('sku')
),
productName: resultSet.getString(
resultSet.getColumnIndex('product_name')
),
category: resultSet.getString(
resultSet.getColumnIndex('category')
),
unitPriceCents: resultSet.getLong(
resultSet.getColumnIndex('unit_price_cents')
),
onHandQty: resultSet.getLong(
resultSet.getColumnIndex('on_hand_qty')
),
reservedQty: resultSet.getLong(
resultSet.getColumnIndex('reserved_qty')
),
availableQty: resultSet.getLong(
resultSet.getColumnIndex('available_qty')
)
});
}
} finally {
resultSet.close();
}
return products;
}
这里有几个细节:
- 使用 LEFT JOIN 查询商品和库存。
- 使用 COALESCE 处理尚未建立库存记录的商品。
- 使用 SQL 参数绑定,避免直接拼接用户输入。
- 使用 ORDER BY 排序。
- 使用完 ResultSet 后及时关闭。
3. 商品修改与停用
修改商品价格:
UPDATE products
SET unit_price_cents = ?
WHERE product_id = ?
AND status = 'ACTIVE';
商品停用:
UPDATE products
SET status = 'INACTIVE'
WHERE product_id = ?;
为什么这里推荐停用而不是直接删除?
因为商品可能已经关联历史订单。
如果直接删除,容易破坏历史业务数据的完整性。
八、库存管理:增加库存与库存预警
商品入库时,库存增加:
UPDATE inventory
SET on_hand_qty = on_hand_qty + ?,
update_time = ?
WHERE warehouse_code = ?
AND product_id = ?;
库存预警查询:
SELECT
product_id,
on_hand_qty,
reserved_qty,
on_hand_qty - reserved_qty AS available_qty
FROM inventory
WHERE warehouse_code = ?
AND on_hand_qty - reserved_qty <= ?;
例如:
仓库设置库存预警阈值为 10 件。
当商品可用库存低于或等于 10 件时,就可以在 ArkUI 页面中展示库存预警。
这里可以进一步扩展:
- 库存预警列表。
- 商品库存变化记录。
- 入库单和出库单。
- 库存盘点。
- 多仓库库存查询。
需要注意,正式的库存系统还应该增加库存流水表,记录每次库存变动的来源、操作人、业务单号和变动数量,以便审计和对账。
九、核心业务:创建订单并完成出库
现在进入最重要的部分。
假设用户创建了一张出库单:
| 商品 | 出库数量 | 单价 |
|---|---|---|
| 无线键盘 | 5 | ¥189.00 |
| 无线鼠标 | 8 | ¥99.00 |
| 27 英寸显示器 | 2 | ¥1,299.00 |
初始库存:
| 商品 | 当前库存 |
|---|---|
| 无线键盘 | 120 |
| 无线鼠标 | 85 |
| 27 英寸显示器 | 36 |
业务要求:
- 校验商品是否存在。
- 校验商品是否处于可销售状态。
- 校验库存是否充足。
- 创建订单主表。
- 保存订单明细。
- 扣减商品库存。
- 全部成功后提交事务。
1. 定义订单模型
export interface OutboundItem {
productId: string;
quantity: number;
}
export interface OutboundRequest {
orderNo: string;
requestId: string;
warehouseCode: string;
customerName: string;
items: OutboundItem[];
}
export interface OutboundResult {
orderNo: string;
duplicate: boolean;
}
2. 实现出库服务
import { WarehouseDatabase } from './WarehouseDatabase';
import { relationalStore } from '@kit.ArkData';
interface OrderLine {
productId: string;
quantity: number;
unitPriceCents: number;
lineAmountCents: number;
}
export class OutboundService {
private static async getAffectedRows(
transaction: relationalStore.Transaction
): Promise<number> {
const resultSet = await transaction.querySql(
'SELECT changes() AS affected'
);
try {
if (resultSet.goToNextRow()) {
return resultSet.getLong(
resultSet.getColumnIndex('affected')
);
}
return 0;
} finally {
resultSet.close();
}
}
static async createOutbound(
request: OutboundRequest
): Promise<OutboundResult> {
const store = WarehouseDatabase.getStore();
// 参数校验
if (
!request.orderNo ||
!request.requestId ||
!request.warehouseCode ||
!request.customerName ||
request.items.length === 0
) {
throw new Error('出库参数不完整');
}
for (let i = 0; i < request.items.length; i++) {
const item = request.items[i];
if (
!item.productId ||
!Number.isInteger(item.quantity) ||
item.quantity <= 0
) {
throw new Error('商品信息不合法');
}
for (let j = i + 1; j < request.items.length; j++) {
if (
request.items[j].productId === item.productId
) {
throw new Error('同一商品不能重复提交明细');
}
}
}
// 创建事务
const transaction = await store.createTransaction();
try {
const now = Date.now();
// 1. 幂等校验
const existing = await transaction.querySql(
`SELECT order_no
FROM orders
WHERE request_id = ?`,
[request.requestId]
);
let existingOrderNo: string | undefined;
try {
if (existing.goToNextRow()) {
existingOrderNo = existing.getString(
existing.getColumnIndex('order_no')
);
}
} finally {
existing.close();
}
// 相同请求已经成功处理,直接返回原订单
if (existingOrderNo !== undefined) {
await transaction.commit();
return {
orderNo: existingOrderNo,
duplicate: true
};
}
// 2. 查询商品价格并计算订单金额
const lines: OrderLine[] = [];
let totalAmountCents = 0;
for (const item of request.items) {
const productResult = await transaction.querySql(
`SELECT unit_price_cents
FROM products
WHERE product_id = ?
AND status = ?`,
[item.productId, 'ACTIVE']
);
let unitPriceCents = -1;
try {
if (productResult.goToNextRow()) {
unitPriceCents = productResult.getLong(
productResult.getColumnIndex(
'unit_price_cents'
)
);
}
} finally {
productResult.close();
}
if (unitPriceCents < 0) {
throw new Error(
`商品不存在或已停用:${item.productId}`
);
}
const lineAmountCents =
item.quantity * unitPriceCents;
totalAmountCents += lineAmountCents;
lines.push({
productId: item.productId,
quantity: item.quantity,
unitPriceCents,
lineAmountCents
});
}
// 3. 创建订单主表
await transaction.insert('orders', {
order_no: request.orderNo,
request_id: request.requestId,
warehouse_code: request.warehouseCode,
customer_name: request.customerName,
status: 'COMPLETED',
total_amount_cents: totalAmountCents,
create_time: now
});
// 4. 扣减库存并保存订单明细
for (const line of lines) {
await transaction.execute(
`UPDATE inventory
SET on_hand_qty = on_hand_qty - ?,
update_time = ?
WHERE warehouse_code = ?
AND product_id = ?
AND on_hand_qty - reserved_qty >= ?`,
[
line.quantity,
now,
request.warehouseCode,
line.productId,
line.quantity
]
);
// 检查库存更新影响的行数
const affectedRows =
await this.getAffectedRows(transaction);
if (affectedRows !== 1) {
throw new Error(
`商品库存不足或库存记录不存在:${line.productId}`
);
}
// 保存订单明细
await transaction.insert('order_items', {
order_no: request.orderNo,
product_id: line.productId,
quantity: line.quantity,
unit_price_cents: line.unitPriceCents,
line_amount_cents: line.lineAmountCents,
create_time: now
});
}
// 5. 全部成功,提交事务
await transaction.commit();
return {
orderNo: request.orderNo,
duplicate: false
};
} catch (error) {
// 任意操作失败,回滚整个事务
try {
await transaction.rollback();
} catch (rollbackError) {
console.error(
`Transaction rollback failed: ${JSON.stringify(rollbackError)}`
);
}
throw error;
}
}
}
3. 这段代码解决了什么?
问题一:商品库存不足
库存更新采用条件 SQL:
UPDATE inventory
SET on_hand_qty = on_hand_qty - ?
WHERE warehouse_code = ?
AND product_id = ?
AND on_hand_qty - reserved_qty >= ?;
不是简单地先读取库存,再直接覆盖库存值。
库存条件和扣减动作在同一条 SQL 中完成,可以避免单纯的先读后写导致的超扣风险。
问题二:订单明细保存失败
因为订单主表、明细表和库存更新处于同一个事务中,所以任意一条明细插入失败,之前执行的库存扣减也会回滚。
问题三:重复提交
使用 request_id 唯一约束。
相同请求再次提交时,返回已经成功创建的订单,不会重复扣减库存。
这里还有一个重要前提:客户端重试时必须复用原来的 requestId,不能每次点击都生成一个新的请求编号。
十、ArkUI 页面如何调用?
业务服务写好之后,页面只负责发起操作和展示结果。
例如:
@Entry
@Component
struct OutboundPage {
@State resultText: string = '等待提交出库单';
build() {
Column({ space: 20 }) {
Text('仓储出库管理')
.fontSize(24)
.fontWeight(FontWeight.Bold)
Button('提交出库订单')
.width('100%')
.onClick(async () => {
try {
const result =
await OutboundService.createOutbound({
orderNo: 'CK202612050001',
requestId: 'REQ202612050001',
warehouseCode: 'WH-SH-01',
customerName: '华东智造有限公司',
items: [
{
productId: 'P-1001',
quantity: 5
},
{
productId: 'P-1002',
quantity: 8
},
{
productId: 'P-1003',
quantity: 2
}
]
});
this.resultText = result.duplicate
? `订单已处理:${result.orderNo}`
: `出库成功:${result.orderNo}`;
} catch (error) {
const err = error as Error;
this.resultText = `出库失败:${err.message}`;
}
})
Text(this.resultText)
.fontSize(16)
}
.padding(20)
.width('100%')
}
}
正式接入时,数据库初始化必须先于页面业务调用完成。
另外,按钮的防重复点击状态应该与服务端幂等机制同时存在,不能只依靠前端禁用按钮。
十一、完整业务验证
下面使用一组合理的仓储业务记录进行验证。
测试一:正常出库
初始化库存:
| 商品 | 库存 |
|---|---|
| 无线键盘 | 120 |
| 无线鼠标 | 85 |
| 27 英寸显示器 | 36 |
订单明细:
| 商品 | 数量 | 单价 |
|---|---|---|
| 无线键盘 | 5 | ¥189.00 |
| 无线鼠标 | 8 | ¥99.00 |
| 27 英寸显示器 | 2 | ¥1,299.00 |
订单金额:
5 × 189 + 8 × 99 + 2 × 1299
= 4335.00 元
预期最终库存:
| 商品 | 出库前 | 出库后 |
|---|---|---|
| 无线键盘 | 120 | 115 |
| 无线鼠标 | 85 | 77 |
| 27 英寸显示器 | 36 | 34 |
同时:
- orders 新增一条记录。
- order_items 新增三条记录。
- 订单金额为 433500 分。
- 订单状态为 COMPLETED。
测试二:库存不足
重新准备一组初始库存:
无线键盘:120
无线鼠标:85
显示器:36
提交:
无线键盘:5
无线鼠标:8
显示器:50
显示器库存不足,第三次库存更新影响行数为 0。
预期:
- 订单主表不新增该订单。
- 订单明细表不新增该订单的明细。
- 键盘库存仍为 120。
- 鼠标库存仍为 85。
- 显示器库存仍为 36。
测试三:重复请求
第一次使用:
requestId = REQ202612050001
出库成功后,再次使用相同 requestId 提交。
预期:
- 返回原有订单编号。
- 不新增订单。
- 不重复扣减库存。
测试四:应用重新启动
完成出库后,退出应用并重新启动。
重新查询订单和库存。
预期:
已经提交的本地数据仍然存在。
以上是代码逻辑对应的验收预期,正式发布前应在指定 SDK、DevEco Studio 和目标设备上完成编译与实测,并记录实际结果。
十二、企业级开发必须继续考虑的六个问题
1. 数据库事务并发
RelationalStore 的事务对象之间相互隔离,但不能理解成多个写事务可以无限并行。
官方文档明确说明:
- 一个 RdbStore 最多同时存在四个事务对象。
- 关系型数据库同一时刻仅支持一个写事务。
- 长时间持有写事务容易增加数据库锁竞争。
所以应缩短事务时间,避免在事务中调用网络接口。
2. 数据库错误码
重点关注:
| 错误码 | 含义 |
|---|---|
| 14800015 | 数据库繁忙 |
| 14800024 | 数据库文件锁定 |
| 14800014 | 数据库实例已关闭 |
| 14800011 | 数据库损坏相关错误 |
对于可以恢复的锁竞争,可以采用有限次数的退避重试。
不要对所有数据库异常进行无限重试。
3. 索引和分页
订单列表不应该一次性加载全部历史记录。
SELECT
order_no,
customer_name,
status,
total_amount_cents,
create_time
FROM orders
WHERE warehouse_code = ?
ORDER BY create_time DESC
LIMIT ? OFFSET ?;
实际开发中可以采用基于创建时间和订单号的游标分页,避免大量数据下 OFFSET 越来越大的性能问题。
4. 数据库版本升级
版本升级应该具备:
- 版本号管理。
- 增量 SQL。
- 迁移失败回滚。
- 迁移前备份策略。
- 升级后的数据完整性检查。
不能因为新增字段就删除原有数据库。
5. 数据安全
需要根据业务数据分级配置数据库安全策略。
尤其是客户信息、业务凭证和用户身份信息,不能仅依靠本地数据库文件隔离。
Preferences 本身不支持通过配置直接加密存储;RelationalStore 可以配置数据库加密能力,但密钥管理也必须纳入设计。
6. 端云数据一致性
这里最容易产生误解。
本篇使用的事务只能保证当前设备本地数据库中的操作原子性。
如果多个仓库管理员同时操作同一个商品库存,本地 SQLite 无法保证多个设备之间的全局库存一致。
生产架构应该进一步扩展:
鸿蒙客户端
|
v
本地 RelationalStore
|
v
本地待同步队列
|
v
HTTPS / API
|
v
企业后端
|
v
服务端权威数据库
|
v
库存校验与业务处理
|
v
同步结果返回客户端
端云同步还需要处理:
- 请求幂等。
- 断网重试。
- 数据冲突。
- 订单状态对账。
- 失败补偿。
- 多设备库存竞争。
不能把本地事务直接等同于分布式事务。
十三、项目总结
通过这次仓储订单管理模块的实战,我们把几个重要知识点串联起来了。
| 知识点 | 在项目中的作用 |
|---|---|
| Preferences | 保存用户配置 |
| RelationalStore | 保存业务结构化数据 |
| SQLite | 本地关系型数据库引擎 |
| RdbStore | 管理数据库实例 |
| SQL | 数据查询和业务更新 |
| RdbPredicates | 条件数据操作 |
| Transaction | 保证多步操作的原子性 |
| ResultSet | 读取查询结果 |
| Index | 优化查询效率 |
| 数据库版本管理 | 支持应用持续升级 |
| 幂等设计 | 防止重复业务请求 |
我认为,鸿蒙应用开发真正进入企业项目之后,不能只关注页面布局、组件交互和网络请求。
当一个应用开始管理订单、库存、审批和业务记录时,数据模型、持久化方案、事务一致性和异常恢复才是更值得深入研究的部分。
本篇完成的是本地仓储业务核心模块。后续还可以在此基础上继续实现离线出库、端云同步、库存预警、订单审计和多仓库管理。
官方技术参考
- HarmonyOS:通过用户首选项实现数据持久化(ArkTS)
- HarmonyOS:通过关系型数据库实现数据持久化(ArkTS)
- HarmonyOS:RelationalStore RdbStore API
- HarmonyOS:RelationalStore Transaction API
开发基线:HarmonyOS SDK API 14+,使用对应 SDK 版本的 DevEco Studio 工程。实际投稿时补充自己的 DevEco Studio 版本、目标设备型号和实际验证记录。
更多推荐




所有评论(0)