Grundlagen der TypeORM-Integration
Richten Sie TypeORM mit NestJS ein, definieren Sie Entitäten und führen Sie grundlegende Datenbankoperationen mit Repositories aus.
Grundlagen der TypeORM-Integration ist eine kostenlose NestJS Enterprise Backend APIs-Lektion auf CoddyKit. Dies ist Lektion 3 von 3. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des NestJS Enterprise Backend APIs-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der NestJS Enterprise Backend APIs-Kurs umfasst insgesamt 3 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
Intro to TypeORM in NestJS
Welcome to integrating TypeORM with NestJS! TypeORM is an Object-Relational Mapper (ORM) that helps you work with databases using TypeScript or JavaScript.
Instead of writing raw SQL queries, you interact with your database using familiar object-oriented programming concepts like classes and objects.
Why Use an ORM?
ORMs like TypeORM offer several benefits:
- Abstraction: No need to write complex SQL.
- Type Safety: With TypeScript, your database interactions are type-checked.
- Portability: Easily switch between different database systems (PostgreSQL, MySQL, SQLite, etc.).
- Productivity: Faster development with less boilerplate code.
Setting Up TypeORM Module
First, we need to install TypeORM and the database driver for your chosen database (e.g., pg for PostgreSQL, sqlite3 for SQLite).
Then, we configure the TypeOrmModule in your main application module (usually AppModule) to establish the database connection.
TypeOrmModule Configuration
Here's how you might configure TypeORM in your app.module.ts. This example uses SQLite for simplicity, which stores data in a file.
We use TypeOrmModule.forRoot() to set up the connection globally.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'sqlite',
database: 'db.sqlite',
entities: [], // We'll add our entities here soon!
synchronize: true, // Auto-create tables (dev only!)
}),
],
controllers: [],
providers: [],
})
export class AppModule {}
Defining Your First Entity
An Entity is a class that maps directly to a database table. Each instance of the entity class represents a row in that table.
We use decorators like @Entity(), @PrimaryGeneratedColumn(), and @Column() to define the table and its columns.
User Entity Example
Let's create a simple User entity. This will map to a user table in our database.
@PrimaryGeneratedColumn()creates an auto-incrementing primary key.@Column()defines a regular column.
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column({ default: true })
isActive: boolean;
}Registering Entities in Module
After defining your entity, you need to tell TypeORM about it. Update your AppModule's TypeOrmModule.forRoot() configuration to include your new User entity.
This allows TypeORM to create the corresponding table in your database.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity'; // Import your entity
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'sqlite',
database: 'db.sqlite',
entities: [User], // Register your User entity here
synchronize: true,
}),
],
controllers: [],
providers: [],
})
export class AppModule {}Introducing Repositories
TypeORM Repositories are objects that provide methods for interacting with a specific entity's table in the database.
You inject a repository into your NestJS service (e.g., UserService) to perform CRUD operations (Create, Read, Update, Delete).
Basic Operations: Create & Read
To use a repository, you inject it using @InjectRepository(). Let's see how to create a new user and retrieve all users.
save(): Inserts a new record or updates an existing one.find(): Retrieves all records for the entity.
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) {}
async createUser(): Promise<User> {
const newUser = this.usersRepository.create({
firstName: 'Coddy',
lastName: 'Kit',
isActive: true,
});
return this.usersRepository.save(newUser);
}
async findAll(): Promise<User[]> {
return this.usersRepository.find();
}
}TypeORM Quick Check
Which decorator is used to mark a class as an entity that maps to a database table in TypeORM?
Recap: TypeORM Basics
You've learned the basics of integrating TypeORM into your NestJS application!
- We configured
TypeOrmModulein ourAppModule. - We defined an Entity using decorators like
@Entity(),@PrimaryGeneratedColumn(), and@Column(). - We understood how to use Repositories to perform basic database operations like creating and reading records.
Next, you'll explore more advanced CRUD operations and data handling techniques!
Häufig gestellte Fragen
Ist die Lektion „Grundlagen der TypeORM-Integration“ kostenlos?
Ja — der vollständige Text von „Grundlagen der TypeORM-Integration“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des NestJS Enterprise Backend APIs-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der NestJS Enterprise Backend APIs-Kurs umfasst insgesamt 3 Lektionen.
Was lerne ich in „Grundlagen der TypeORM-Integration“?
Richten Sie TypeORM mit NestJS ein, definieren Sie Entitäten und führen Sie grundlegende Datenbankoperationen mit Repositories aus. Du übst NestJS Enterprise Backend APIs mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um NestJS Enterprise Backend APIs zu starten?
Keine Vorkenntnisse erforderlich. NestJS Enterprise Backend APIs auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 3.
Wie lange dauert die Lektion „Grundlagen der TypeORM-Integration“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser NestJS Enterprise Backend APIs-Lektion Code schreiben und ausführen?
Ja. Jede NestJS Enterprise Backend APIs-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Dependency Injection erklärt
- DTOs und Validierungspipes
- Grundlagen der TypeORM-Integration