Quickstart Guide
Relevant source files
The following files were used as context for generating this wiki page:
SeaORM 2.0 is a comprehensive Object-Relational Mapping (ORM) library for Rust, designed to facilitate the development of web services by providing familiar concepts from popular dynamic language ORMs. It supports advanced relational modeling, including 1-1, 1-N, M-N, and self-referential relationships, while offering both asynchronous and synchronous execution modes.
This guide provides a technical overview of setting up and using SeaORM, focusing on the Entity-First workflow, ActiveModel persistence, and efficient querying strategies. It covers the core architectural components that enable developers to build REST, GraphQL, and gRPC APIs with minimal boilerplate.
Sources: src/lib.rs:24-42, README.md:14-25
Core Architectural Components
SeaORM is structured around several key modules that handle database connections, entity definitions, and query execution.
| Component | Description |
|---|---|
| Entity | Defines the schema and relationships of a database table. |
| Model | A read-only Rust struct representing a row in a table. |
| ActiveModel | A mutable struct used for insertion, updates, and deletion. |
| DbConn | Manages the connection pool and execution of SQL statements. |
| Schema Registry | Detects changes in entities to sync database schemas automatically. |
Sources: src/lib.rs:567-582, CLAUDE.md:105-110
Workflow Overview
SeaORM supports two primary workflows: Schema-First (using migrations) and Entity-First. In the Entity-First workflow, the code serves as the source of truth, and SeaORM handles the creation and synchronization of database tables.
The diagram shows the transition from code definitions to database state and subsequent data operations.
Sources: src/lib.rs:168-176, CLAUDE.md:105-110
Defining Entities (SeaORM 2.0 Format)
In SeaORM 2.0, entities are defined using the #[sea_orm::model] attribute. Relationships are declared directly within the Model struct using specialized types like HasOne and HasMany.
Relationship Mapping
Relationships are defined with specific attributes to manage foreign keys and junction tables:
- Has-One:
#[sea_orm(has_one)] - Has-Many:
#[sea_orm(has_many)] - Belongs-To:
#[sea_orm(belongs_to, from = "local_col", to = "remote_col")] - Many-to-Many: Uses
viato specify a junction table.
Sources: CLAUDE.md:15-54, src/lib.rs:114-135
#[sea_orm::model]
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "user")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
#[sea_orm(has_one)]
pub profile: HasOne<super::profile::Entity>,
}
Sources: CLAUDE.md:15-28, src/lib.rs:114-128
Data Persistence with ActiveModel
ActiveModel is the primary interface for performing write operations. It utilizes a fluent builder API to handle nested persistence, automatically resolving dependencies between related objects.
Nested Persistence Logic
When saving a graph of objects (e.g., a User with a Profile and multiple Posts), SeaORM determines the correct topological order for insertion to satisfy foreign key constraints.
The sequence illustrates how SeaORM handles complex object graphs in a single logical operation.
Sources: src/lib.rs:178-198, CLAUDE.md:80-100
Querying and Data Loading
SeaORM provides a "Smart Entity Loader" to solve the N+1 query problem. It chooses the most efficient SQL strategy based on the relationship type:
- 1-1 Relations: Uses SQL
JOIN. - 1-N Relations: Uses a Data Loader (multiple targeted queries with
INclauses).
Eager Loading Example
let user = user::Entity::load()
.filter_by_id(42)
.with(profile::Entity) // Uses JOIN
.with(post::Entity) // Uses Data Loader
.one(db)
.await?;
Sources: src/lib.rs:140-165, CLAUDE.md:92-103
Synchronous vs Asynchronous Execution
SeaORM supports two execution environments. The standard sea-orm crate is asynchronous (relying on SQLx), while sea-orm-sync provides a synchronous API suitable for CLI tools and lightweight applications.
| Feature | Async (sea-orm) | Sync (sea-orm-sync) |
|---|---|---|
| Runtime | Required (Tokio/async-std) | None required |
| Driver | SQLx | Rusqlite / Native drivers |
| Best For | High-concurrency web servers | CLI tools, embedded, simple scripts |
Sources: sea-orm-sync/src/lib.rs:215-220, sea-orm-sync/CLAUDE.md:1-15
Development and Testing
For local development, SeaORM provides tools for unit and integration testing. Unit tests utilize a MockDatabase to simulate database responses without requiring a live instance.
Testing Commands
- Unit Tests:
cargo test --workspace - Integration Tests (SQLite):
DATABASE_URL="sqlite::memory:" cargo test --all --features default,sqlx-sqlite,runtime-async-std-native-tls - Clippy:
cargo clippy --all
Sources: CONTRIBUTING.md:58-85, DEVELOPMENT.md:1-40
Summary
SeaORM 2.0 streamlines Rust database development by offering an Entity-First workflow, smart relationship loading, and a powerful ActiveModel API for complex data persistence. By abstracting the complexities of SQL joins and dependency management, it allows developers to focus on application logic while maintaining high performance and type safety.
Sources: src/lib.rs:24-42, CLAUDE.md:1-10