Isaac.

database

Prisma ORM Getting Started

Build type-safe applications with Prisma ORM.

By Emem IsaacApril 30, 20242 min read
#prisma#orm#typescript#database#type-safe
Share:

A Simple Analogy

Prisma is like a GPS for your database. It knows the routes (schema) and gets you where you need to go (queries).


Why Prisma?

  • Type-safe: Full TypeScript support
  • Auto-complete: IDE suggestions work great
  • Migrations: Version control for schema
  • Intuitive: Easy to learn and use
  • Multi-database: Works with many databases

Installation

npm install @prisma/client
npm install -D prisma
npx prisma init

Schema Definition

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id      Int     @id @default(autoincrement())
  title   String
  content String?
  author  User    @relation(fields: [authorId], references: [id])
  authorId Int
}

Basic Queries

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

// Create
const user = await prisma.user.create({
  data: {
    email: 'alice@example.com',
    name: 'Alice'
  }
});

// Read
const users = await prisma.user.findMany();
const user = await prisma.user.findUnique({
  where: { email: 'alice@example.com' }
});

// Update
const updated = await prisma.user.update({
  where: { id: 1 },
  data: { name: 'Alice Updated' }
});

// Delete
await prisma.user.delete({ where: { id: 1 } });

Relationships

// Create with relation
const user = await prisma.user.create({
  data: {
    email: 'bob@example.com',
    posts: {
      create: [
        { title: 'First Post' },
        { title: 'Second Post' }
      ]
    }
  }
});

// Include related data
const userWithPosts = await prisma.user.findUnique({
  where: { id: 1 },
  include: { posts: true }
});

Best Practices

  1. Type safety: Leverage TypeScript
  2. Migrations: Use Prisma migrate
  3. Seeding: Define seed data
  4. Error handling: Catch Prisma errors
  5. Connection pooling: Use via datasource

Related Concepts

  • Drizzle ORM
  • TypeORM
  • Sequelize
  • Raw SQL

Summary

Prisma provides type-safe database access with intuitive queries and automatic migrations.

Share:

Written by Emem Isaac

Expert Software Engineer with 15+ years of experience building scalable enterprise applications. Specialized in ASP.NET Core, Azure, Docker, and modern web development. Passionate about sharing knowledge and helping developers grow.

Ready to Build Something Amazing?

Let's discuss your project and explore how my expertise can help you achieve your goals. Free consultation available.

💼 Trusted by 50+ companies worldwide | ⚡ Average response time: 24 hours