이 문서는 Google Cloud Translation API를 사용해 자동 번역되었습니다.
어떤 문서는 원문을 읽는게 나을 수도 있습니다.
개체 관계형 매핑을 위해 TypeORM과 함께 TypeScript 사용
ORM(개체 관계형 매핑)은 개발자가 개체 지향 모델을 관계형 데이터베이스에 매핑할 수 있는 기술입니다. TypeORM은 데코레이터를 사용하고 MySQL, PostgreSQL 등과 같은 다양한 데이터베이스와 호환되는 TypeScript 및 JavaScript용으로 널리 사용되는 ORM 라이브러리입니다.
세부 사항을 살펴보기 전에 설치해야 하는 몇 가지 전제 조건이 있습니다.
TypeORM을 사용하려면 먼저 설치해야 합니다. 다음 명령을 사용하여 전역적으로 설치할 수 있습니다.
npm install -g typeorm
To set up a project with TypeScript and TypeORM, we need to create a new directory and initialize it with npm using the following command:
npm 초기화 -y
그런 다음 필요한 종속 항목을 설치해야 합니다. npm을 사용하여 다음 종속성을 설치할 수 있습니다.
npm install --save-dev typescript ts-node @types/node @types/express typeorm mysql2
typescript
is required to compile TypeScript code to JavaScript.ts-node
is required to run TypeScript code directly without compiling it.@types/node
and @types/express
are TypeScript definitions for Node.js and Express.typeorm
is the TypeORM library.mysql2
is a MySQL driver for TypeORM.Next, we need to create a TypeScript configuration file, tsconfig.json
, in the root directory of the project with the following content:
{
"컴파일러 옵션": {
"모듈": "commonjs",
"esModuleInterop": 참,
"대상": "es6",
"moduleResolution": "노드",
"sourceMap": 참,
"outDir": "거리"
},
"포함": ["src/**/*"],
"제외": ["node_modules"]
}
In this configuration, we have specified that we want to compile the TypeScript code to ES6 JavaScript, with source maps enabled and output in the dist
directory. We have also specified that we want to include all the .ts
files in the src
directory and exclude the node_modules
directory.
In TypeORM, an entity is a TypeScript class that represents a database table. To create an entity, we need to define a class with properties that correspond to the columns in the table. We can also use decorators to specify the table name, column types, primary keys, etc.
Let's create an entity for a User
table with the following properties:
id
: a unique identifier for the user.username
: the username of the user.password
: the password of the user.Create a new file User.ts
in the src/entity
directory with the following content:
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@실재()
내보내기 클래스 사용자 {
@PrimaryGeneratedColumn()
ID 번호;
@열()
사용자 이름: 문자열;
@열()
암호: 문자열;
}
In this code, we have used the @Entity()
decorator to specify that this class is an entity. We have also used the @PrimaryGeneratedColumn()
decorator to specify that the id
property is the primary key for the table, and it will be generated automatically. Similarly, we have used the @Column()
decorator to specify that the username
and password
properties are columns in the table.
To use TypeORM, we need to create a connection to the database. We can create a connection using the createConnection()
method from the typeorm
module.
Create a new file index.ts
in the src
directory with the following content:
"반영-메타데이터" 가져오기;
import { createConnection } from "typeorm";
"./entity/User"에서 { 사용자 } 가져오기;
createConnection().then(비동기 연결 => {
console.log("데이터베이스에 새 사용자를 추가하는 중...");
const 사용자 = 새 사용자();
user.username = "john_doe";
user.password = "my_password";
await connection.manager.save(사용자);
console.log("ID가 " + user.id 인 새 사용자를 저장했습니다.
console.log("데이터베이스에서 사용자 로드 중...");
const 사용자 = await connection.manager.find(사용자);
console.log("로드된 사용자: ", users);
}).catch(오류 => console.log(오류));
In this code, we have imported the reflect-metadata
module, which is required to use decorators. Then, we have imported the createConnection()
function from the typeorm
module and the User
class from the entity/User.ts
module.
We have used the createConnection()
function to create a connection to the default database. Then, we have inserted a new user into the database using the save()
method of the connection manager. Finally, we have loaded all the users from the database using the find()
method of the connection manager.
To run the application, we need to compile the TypeScript code to JavaScript and then run the JavaScript code using ts-node
. We can do this using the following command:
npx ts-node src/index.ts
이것은 TypeScript 코드를 컴파일하고 index.ts
파일을 실행하여 데이터베이스에 새 사용자를 삽입하고 데이터베이스에서 모든 사용자를 로드합니다.
TypeORM이 포함된 TypeScript는 ORM의 강력한 조합입니다. 데코레이터의 도움으로 데이터베이스 테이블에 매핑되는 엔터티를 쉽게 만들 수 있습니다. 또한 엔터티 간의 관계를 만들고 연결 관리자를 사용하여 데이터베이스를 쿼리하고 트랜잭션을 수행할 수 있습니다. TypeORM은 다양한 데이터베이스를 지원하며 간단하고 직관적인 API를 제공합니다.