SeaORM
问题
SeaORM 和 SQLx/Diesel 有什么区别?
答案
SeaORM 是基于 SQLx 的异步 ORM,提供类似 ActiveRecord 的体验。
Entity 定义
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "users")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
pub email: String,
pub created_at: DateTimeUtc,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::post::Entity")]
Posts,
}
impl ActiveModelBehavior for ActiveModel {}
CRUD 操作
use sea_orm::*;
// 查询
let user: Option<user::Model> = User::find_by_id(1)
.one(&db)
.await?;
// 条件查询
let users: Vec<user::Model> = User::find()
.filter(user::Column::Name.contains("alice"))
.order_by_desc(user::Column::CreatedAt)
.limit(10)
.all(&db)
.await?;
// 插入
let user = user::ActiveModel {
name: Set("Alice".to_string()),
email: Set("alice@example.com".to_string()),
..Default::default()
};
let result = User::insert(user).exec(&db).await?;
// 更新
let mut user: user::ActiveModel = User::find_by_id(1)
.one(&db).await?
.unwrap()
.into();
user.name = Set("Bob".to_string());
user.update(&db).await?;
三者对比
| 维度 | SQLx | Diesel | SeaORM |
|---|---|---|---|
| 风格 | 原始 SQL | DSL | ORM |
| 类比 | Go database/sql | - | TypeORM |
| 学习曲线 | 低 | 中 | 低 |
| 灵活性 | 最高 | 中 | 中 |
| 代码生成 | 无 | schema.rs | sea-orm-cli |
常见面试问题
Q1: SeaORM 适合什么场景?
答案:
- 快速开发 CRUD 应用
- 团队熟悉 ActiveRecord/TypeORM 模式
- 需要异步支持
- 不想写原始 SQL
不适合:需要极致性能或非常复杂的 SQL 查询的场景。