📜  typeorm IN - Javascript (1)

📅  最后修改于: 2023-12-03 15:20:42.791000             🧑  作者: Mango

TypeORM in JavaScript

TypeORM is a popular Object-Relational Mapping (ORM) library for Node.js and browsers. It enables developers to work with databases using an Object-Oriented approach and provides various features for database schema and data manipulation.

Installation

To start using TypeORM in a JavaScript project, you need to install it using the following command:

npm install typeorm --save
Configuration

Before using TypeORM, you need to configure it with the database you want to use. This is done using a JSON file called ormconfig.json or by setting environment variables. Here's an example of how to set up a SQLite database:

{
  "type": "sqlite",
  "database": "database.sqlite",
  "synchronize": true,
  "logging": false,
  "entities": [
    "src/entities/*.js"
  ],
  "migrations": [
    "src/migrations/*.js"
  ],
  "subscribers": [
    "src/subscribers/*.js"
  ],
  "cli": {
    "entitiesDir": "src/entities",
    "migrationsDir": "src/migrations",
    "subscribersDir": "src/subscribers"
  }
}
Entities

Entities are classes that represent database tables. They define the schema and the relationships between tables. Here's an example of an entity for a user table:

import { Entity, Column, PrimaryGeneratedColumn } from "typeorm";

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  firstName: string;

  @Column()
  lastName: string;

  @Column()
  email: string;
}
Repository

Repositories are used to perform CRUD operations on the entities. They provide methods such as find, save, update, and delete. Here's an example of how to use a repository to find all users:

import { getRepository } from "typeorm";
import { User } from "./entities/User";

async function getUsers() {
  const userRepository = getRepository(User);
  const users = await userRepository.find();
  console.log(users);
}
Conclusion

TypeORM is a powerful ORM library for JavaScript that provides many features for database management. By using classes and decorators, developers can easily define database tables and relationships, and manipulate data using repositories. If you're building a Node.js or browser-based application with a database, you should definitely consider using TypeORM.