Configurando o Prisma ORM
Configure e integre o Prisma ORM ao seu projeto Next.js para interagir com diversos bancos de dados.
Configurando o Prisma ORM é uma aula grátis de Next.js 15 Fullstack (App Router + Server Actions) no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Next.js 15 Fullstack (App Router + Server Actions), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Next.js 15 Fullstack (App Router + Server Actions) inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
What is an ORM?
Welcome! In this lesson, we'll set up Prisma ORM in a Next.js project. But first, what's an ORM?
- ORM stands for Object-Relational Mapping.
- It's a technique that lets you interact with your database using your programming language's objects instead of writing raw SQL.
- Think of it as a translator between your code (e.g., JavaScript objects) and your database (e.g., SQL tables).
Why Choose Prisma?
Prisma is a modern ORM that's popular with Next.js for good reasons:
- Type Safety: It generates a type-safe client, preventing many runtime errors.
- Developer Experience: Intuitive API, powerful migrations, and automatic code completion.
- Modern Stack: Designed for TypeScript and modern JavaScript, fitting perfectly with Next.js.
- Database Support: Works with PostgreSQL, MySQL, SQLite, SQL Server, and MongoDB.
Installing Prisma
Let's start by adding Prisma to your Next.js project. You'll need two main packages:
prisma: The Prisma CLI (Command Line Interface) for development tasks.@prisma/client: The Prisma Client library for interacting with your database in code.
Run this command in your project's root:
npm install prisma @prisma/clientInitialize Prisma
After installation, you need to initialize Prisma in your project. This command sets up the basic Prisma structure, including the prisma/schema.prisma file.
It also creates a .env file to hold your database connection string.
npx prisma initConnect Your Database
The .env file created by prisma init contains a DATABASE_URL variable. This is where you tell Prisma how to connect to your database.
For local development, SQLite is often used for simplicity. For production, you might use PostgreSQL or MySQL.
# .env
DATABASE_URL="postgresql://user:password@host:port/database?schema=public"
# Example for SQLite (local file)
# DATABASE_URL="file:./dev.db"The Prisma Schema File
Your prisma/schema.prisma file is the heart of your Prisma setup. It defines three key blocks:
datasource: Specifies your database provider (e.g.,postgresql,sqlite).generator: Configures the Prisma Client (usuallyprisma-client-js).model: Defines your database tables (models) and their fields.
Defining Your First Model
Let's define a simple User model in your prisma/schema.prisma file. This model will represent a table in your database.
id: Unique identifier, auto-incrementing.email: User's email, must be unique.name: User's name, optional.
// prisma/schema.prisma
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}Generating Prisma Client
After defining or changing your models in schema.prisma, you must generate the Prisma Client. This command reads your schema and creates the type-safe client library.
This client is what you'll import and use in your Next.js application to interact with your database.
npx prisma generateApplying Migrations
To create or update your database tables based on your schema.prisma, you use migrations. The migrate dev command:
- Compares your schema to the database.
- Generates SQL migration files.
- Applies these migrations to your database.
It also generates the Prisma Client automatically after migration.
npx prisma migrate dev --name initUsing Prisma Client
Once Prisma is set up and generated, you can use the PrismaClient in your Next.js server components or API routes to perform database operations. Here's a basic example:
import { PrismaClient } from '@prisma/client';
async function main() {
const prisma = new PrismaClient();
console.log("Prisma Client successfully initialized!");
// In a real app, you'd perform database operations:
// const users = await prisma.user.findMany();
// console.log(users);
await prisma.$disconnect();
console.log("Prisma Client disconnected.");
}
main().catch(console.error);Quick Check: Prisma Commands
You've learned about several key Prisma CLI commands. Which command is used to generate the type-safe Prisma Client after you've modified your schema.prisma file?
Recap: Setting Up Prisma
Great job! You've learned the essential steps to integrate Prisma ORM into your Next.js project:
- Installed Prisma CLI and client.
- Initialized Prisma and configured your database URL.
- Defined data models in
schema.prisma. - Generated the Prisma Client.
- Applied migrations to sync your schema with the database.
- Understood how to instantiate and use
PrismaClient.
Next, we'll dive into performing CRUD operations with Prisma!
Perguntas Frequentes
A aula “Configurando o Prisma ORM” é grátis?
Sim — o texto completo de “Configurando o Prisma ORM” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Next.js 15 Fullstack (App Router + Server Actions), atualize para CoddyKit PRO. O curso de Next.js 15 Fullstack (App Router + Server Actions) inclui 4 aulas no total.
O que vou aprender em “Configurando o Prisma ORM”?
Configure e integre o Prisma ORM ao seu projeto Next.js para interagir com diversos bancos de dados. Você pratica Next.js 15 Fullstack (App Router + Server Actions) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Next.js 15 Fullstack (App Router + Server Actions)?
Nenhuma experiência prévia é necessária. Next.js 15 Fullstack (App Router + Server Actions) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.
Quanto tempo leva a aula “Configurando o Prisma ORM”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Next.js 15 Fullstack (App Router + Server Actions)?
Sim. Cada aula de Next.js 15 Fullstack (App Router + Server Actions) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Configurando o Prisma ORM
- CRUD com Server Actions
- Migrações de esquema de banco de dados
- Povoamento do Banco de Dados e Agrupamento de Conexões