SeaORM 集成 #

添加依赖 #

toml
[dependencies]
sea-orm = { version = "0.12", features = ["sqlx-postgres", "runtime-tokio-native-tls", "macros"] }

连接数据库 #

rust
use sea_orm::{Database, DatabaseConnection};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let db: DatabaseConnection = Database::connect("postgres://user:pass@localhost/db")
        .await
        .expect("Failed to connect");
    
    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(db.clone()))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

实体定义 #

rust
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "users")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i32,
    pub name: String,
    pub email: String,
    pub created_at: DateTime,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}

CRUD 操作 #

查询所有 #

rust
use sea_orm::*;

pub async fn get_all_users(db: &DatabaseConnection) -> Result<Vec<users::Model>, DbErr> {
    users::Entity::find()
        .all(db)
        .await
}

按 ID 查询 #

rust
pub async fn get_user_by_id(db: &DatabaseConnection, id: i32) -> Result<Option<users::Model>, DbErr> {
    users::Entity::find_by_id(id)
        .one(db)
        .await
}

创建 #

rust
pub async fn create_user(
    db: &DatabaseConnection,
    name: String,
    email: String,
) -> Result<users::Model, DbErr> {
    let user = users::ActiveModel {
        name: Set(name),
        email: Set(email),
        ..Default::default()
    };
    
    user.insert(db).await
}

更新 #

rust
pub async fn update_user(
    db: &DatabaseConnection,
    id: i32,
    name: Option<String>,
    email: Option<String>,
) -> Result<Option<users::Model>, DbErr> {
    let user = users::Entity::find_by_id(id)
        .one(db)
        .await?;
    
    match user {
        Some(user) => {
            let mut user: users::ActiveModel = user.into();
            
            if let Some(name) = name {
                user.name = Set(name);
            }
            if let Some(email) = email {
                user.email = Set(email);
            }
            
            Ok(Some(user.update(db).await?))
        }
        None => Ok(None),
    }
}

删除 #

rust
pub async fn delete_user(db: &DatabaseConnection, id: i32) -> Result<bool, DbErr> {
    let result = users::Entity::delete_by_id(id)
        .exec(db)
        .await?;
    
    Ok(result.rows_affected > 0)
}

在 Actix Web 中使用 #

rust
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use sea_orm::*;

#[actix_web::get("/users")]
async fn list_users(db: web::Data<DatabaseConnection>) -> impl Responder {
    match users::Entity::find().all(db.get_ref()).await {
        Ok(users) => HttpResponse::Ok().json(users),
        Err(e) => HttpResponse::InternalServerError()
            .json(serde_json::json!({ "error": e.to_string() })),
    }
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let db = Database::connect("postgres://user:pass@localhost/db")
        .await
        .expect("Failed to connect");
    
    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(db.clone()))
            .service(list_users)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

下一步 #

继续学习 身份验证,了解安全特性!

最后更新:2026-03-29