
@BeforeInsert 데코레이터는 엔터티가 데이터베이스에 삽입되기 전에 실행되어야 하는 메서드를 지정합니다.
이 메서드는 삽입 작업이 수행되기 전에 자동으로 호출됩니다.
주로 엔터티에 대한 일부 초기화나 가공 작업을 수행하는 데 사용됩니다.
그리고 항상 적용되는게 아닙니다.
import { Entity, Column, BeforeInsert } from 'typeorm';
@Entity()
class User {
@Column()
name: string;
@BeforeInsert()
doSomethingBeforeInsert() {
// This method will be called before inserting the entity into the database
console.log('Doing something before insert...');
}
}
@Eager 데코레이터는 관련된 엔터티를 즉시 로드하도록 지정합니다. 기본적으로 TypeORM은 연관된 엔터티를 지연로드합니다.
즉시 로드를 사용하면 쿼리 실행 시에 관련된 엔터티를 함께 로드하므로 추가적인 쿼리가 발생하지 않습니다.
import { Entity, OneToMany, JoinColumn, Eager } from 'typeorm';
@Entity()
class User {
@OneToMany(type => Post, post => post.user)
@JoinColumn()
@Eager(['posts'])
posts: Post[];
}
cascade는 연관된 엔터티에 대한 특정 작업을 부모 엔터티에 전파할지 여부를 설정합니다.
예를 들어, 부모 엔터티를 저장할 때 자동으로 연관된 엔터티도 저장하거나 삭제할 수 있습니다.
import { Entity, OneToMany, JoinColumn } from 'typeorm';
@Entity()
class User {
@OneToMany(type => Post, post => post.user, { cascade: true })
@JoinColumn()
posts: Post[];
}