-TypeORM Starting Guide

Installed a.

Use the CLI commands provided by the government to set up a project

NPM install TypeORM -g

Typeorm init –name [MyProject] –database [mysql] typeorm init –name [MyProject] –database [mysql

Database configuration options include mysql, Mariadb, Postgres, SQLite, MSSQL, Oracle, mongodb, Cordova, React-Native, Expo, and Nativescript. Execute the following instructions to create the project

typeorm init --name ormStudy --database mysql

Now the project structure

OrmStudy ├ ─ ─ SRC/code/TypeScript │ ├ ─ ─ the entity / / store entity model (database) the location of the │ │ └ ─ ─ the User. The ts / / sample entity │ ├ ─ ─ migration/directory/storage migration │ └ ─ ─ index. Ts / / program execution master file ├ ─ ─ the gitignore / / gitignore file ├ ─ ─ ormconfig. Json / / ORM and database connection configuration ├ ─ ─ package. The json / / node ├─ ├─ └─ trash // TypeScript ├─ └─ trash // TypeScriptCopy the code

Install the dependency CD ormStudy NPM I

MySQL > CREATE database CREATE SCHEMA ‘orm_test’; Edit ormconfig.json for your own database link

{
   "type": "mysql"."host": "localhost"."port": 3306."username": "root"."password": "xxxx"."database": "orm_test"."synchronize": true."logging": false."entities": [
      "src/entity/**/*.ts"]."migrations": [
      "src/migration/**/*.ts"]."subscribers": [
      "src/subscriber/**/*.ts"]."cli": {
      "entitiesDir": "src/entity"."migrationsDir": "src/migration"."subscribersDir": "src/subscriber"}}Copy the code

Create an entity

To create an entity, you first need to create a model, that is, a table in the database, using the case model Photo of the official document

export class Photo {
    id: number;
    name: string;
    description: string;
    filename: string;
    views: number;
}
Copy the code

In a database, individuals of each type of data object are called entities. In TypeOrm, entities are models decorated with the @Entitiy decorator

Using the Photo model data object as an entity, a brief introduction to the decorator used below

  1. @entity decorates as an Entity
  2. @column is decorated as a database Column
  3. @primaryGeneratedColumn Enables the ID column to be generated automatically

Create photo.ts under SRC /entity and write

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

@Entity(a)export class Photo {
    @PrimaryGeneratedColumn(a)// The id column is automatically generated
    id: number;

    @Column({
        length: 100.// Column data type
    })
    name: string;

    @Column("text")// Column data type
    description: string;

    @Column(a)filename: string;

    @Column("double")// Column data type
    views: number;
    
    @Column(a)isPublished: boolean;
}
Copy the code

At this point, we start the project NPM start to open MySQL to query the table

Creating a successful

Create a database connection

Increased 1.

After creating the entity, change the contents of SRC /index.ts to the ts code below and start the project again

import "reflect-metadata";
import { createConnection } from "typeorm";
import { Photo } from "./entity/Photo";

createConnection()
  .then(async (connection) => {
    let photo = new Photo();
    photo.name = "Me and Bears";
    photo.description = "I am near polar bears";
    photo.filename = "photo-with-bears.jpg";
    photo.views = 1;
    photo.isPublished = true;

    await connection.manager.save(photo);
    console.log("Photo has been saved");
  })
  .catch((error) = > console.log(error));
Copy the code

Start the project NPM start

Looking at the Photo table, you see that all the attributes of the Photo object in the code above have been written to the table

Check 2.

Change the annotated portion of index.ts to the following code

/* await connection.manager.save(photo); console.log("Photo has been saved"); * /
const photos = await connection.manager.find(Photo);
console.log("photos: ", photos);
Copy the code

Start again and watch the terminal output to get what was just entered into the database

3. Change

Now let’s try using Repository instead of EntityManager and change this section of index.ts to the following code. There are methods for refactoring EntityManager in the comments

/ / to add
/* // before changing: await connection.manager.save(photo); console.log("Photo has been saved"); // Let photoRepository = connection.getrepository (Photo); await photoRepository.save(photo); console.log("Photo has been saved"); * /
/ / check
/* // before changing: const photos = await connection.manager.find(Photo); console.log("photos: ", photos); // Let photoRepository = connection.getrepository (Photo); let savedPhotos = await photoRepository.find(); console.log("All photos from the db: ", savedPhotos); * /
/ / change
let photoRepository = connection.getRepository(Photo);
let photoToUpdate = await photoRepository.findOne(1);
photoToUpdate.name = "Me, my friends and polar bears";
await photoRepository.save(photoToUpdate);
Copy the code

Change the name of photo with id 1 to “Me, my friends and Polar bears”

4. Delete

Change the annotated portion of index.ts to the following code

/* let photoToUpdate = await photoRepository.findOne(1); photoToUpdate.name = "Me, my friends and polar bears"; await photoRepository.save(photoToUpdate); * /
let photoToRemove = await photoRepository.findOne(1);
await photoRepository.remove(photoToRemove);
Copy the code

After startup, the photo with ID =1 is removed from the database

So far, we have completed a simple add, delete, change and check MySQL through TypeORM operation