Implement Create Operation
Follow the step-by-step instructions to create an entity and save an address to a MySQL database.
Connecting the TypeORM entity and repository
Now we’ve learned how to configure TypeORM within our app. In this lesson, we’ll dive into creating entities and repositories. We’ll also explore how to update our service methods and connect these key components.
Create an entity
An entity represents a database table and its data. Below is AddressEntity with the @Entity() decorator that marks it as a TypeORM entity. The name property specifies the table name in the database.
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn }from 'typeorm';@Entity({name:'address'})export class AddressEntity {@PrimaryGeneratedColumn()id: number;@Column()address_line: string;@Column()post_code: string;@Column()state: string;@CreateDateColumn()created_date: Date;@UpdateDateColumn()updated_date: Date;}
In AddressEntity, we utilize several decorators to define the table fields, each serving a specific purpose.
@PrimaryGeneratedColumn: This defines a primary key column in the database. It generates unique identifiers automatically, ensuring each record has a distinct identifier. In our example, theidproperty is marked with this decorator, making it the primary key of theaddresstable. Primary keys are essential for uniquely identifying records in the table.@Column: ...