Введение в Prisma ORM
Изучите, что такое Prisma, каковы её преимущества и как настроить её в проекте Next.js.
«Введение в Prisma ORM» — бесплатный урок Next.js 15 Fullstack Web Apps на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Next.js 15 Fullstack Web Apps, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Next.js 15 Fullstack Web Apps содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
What is an ORM? Meet Prisma!
Welcome to working with databases in Next.js! Often, you'll hear about an ORM, or Object-Relational Mapping. An ORM helps you interact with your database using your preferred programming language (like JavaScript/TypeScript) instead of writing raw SQL.
Prisma is a modern, open-source ORM that makes working with databases intuitive and type-safe. It's a fantastic tool for Next.js applications.
Why Choose Prisma for Next.js?
Prisma offers several key advantages for your Next.js projects:
- Type-Safety: It generates a type-safe client based on your database schema, catching errors at compile time.
- Developer Experience: Provides excellent auto-completion and readability for database queries.
- Migrations: Helps manage changes to your database schema over time in a controlled way.
- Modern Tooling: Integrates smoothly with modern JavaScript/TypeScript workflows and serverless environments.
Prisma's Core Components
Prisma isn't just one tool; it's a suite of tools that work together:
- Prisma Client: An auto-generated, type-safe query builder for your database. This is what you'll use in your code.
- Prisma Migrate: A migration system to evolve your database schema and keep it in sync with your Prisma schema.
- Prisma Studio: A visual GUI to view and edit data in your database.
Prerequisites for Setup
Before we dive into setting up Prisma in your Next.js project, make sure you have these:
- An existing Next.js project (we'll assume you have one ready).
- Node.js and npm/yarn installed on your machine.
- A database. For local development, SQLite is easy to start with, or you can use PostgreSQL, MySQL, SQL Server, or MongoDB.
Installing Prisma Packages
First, you need to install the Prisma CLI and the Prisma Client library as development dependencies in your Next.js project. Open your terminal in your project's root directory and run:
npm install prisma @prisma/clientInitializing Prisma in Your Project
After installation, you'll initialize Prisma in your project. This command sets up the necessary files for Prisma to work. Run this in your terminal:
npx prisma initWhat `prisma init` Does
The npx prisma init command performs two important actions:
- It creates a new directory named
prismain your project root, containing a file calledschema.prisma. This file defines your database schema. - It creates a
.envfile in your project root. This file is used to store environment variables, most importantly your database connection URL.
Exploring `schema.prisma` Structure
The prisma/schema.prisma file is central to Prisma. It's where you define your database models and connection details. Here's what it looks like initially:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}Configuring Your Database URL
The .env file created earlier is where you'll specify your database connection string. For local development, you might use SQLite, which is file-based. Update your .env file to point to your database:
# .env
DATABASE_URL="file:./dev.db"Quick Check: Prisma Setup
You've learned about Prisma's purpose and initial setup steps. Let's test your understanding!
Recap: Getting Started with Prisma
In this lesson, we introduced Prisma ORM, understanding its role in bridging your application code with your database. We covered its key benefits like type-safety and improved developer experience, and explored its core components: Prisma Client, Migrate, and Studio.
You also learned the initial steps to integrate Prisma into a Next.js project, including installing the necessary packages and using npx prisma init to set up your schema.prisma and .env files. You're now ready to define your database schema!
Часто задаваемые вопросы
Урок «Введение в Prisma ORM» бесплатный?
Да — полный текст урока «Введение в Prisma ORM» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Next.js 15 Fullstack Web Apps, подпишись на CoddyKit PRO. Курс Next.js 15 Fullstack Web Apps содержит 4 уроков всего.
Чему я научусь в уроке «Введение в Prisma ORM»?
Изучите, что такое Prisma, каковы её преимущества и как настроить её в проекте Next.js. Ты практикуешь Next.js 15 Fullstack Web Apps с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Next.js 15 Fullstack Web Apps?
Предыдущий опыт не требуется. Next.js 15 Fullstack Web Apps на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Введение в Prisma ORM»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Next.js 15 Fullstack Web Apps?
Да. Каждый урок Next.js 15 Fullstack Web Apps включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Введение в Prisma ORM
- Проектирование схемы Prisma и миграции
- Операции CRUD с Prisma Client
- Связи и расширенные запросы с Prisma