TypeORM을 사용해보자 (2)
NestJS에서 TypeORM을 사용해보자
서론
저번 게시글에서는 TypeORM 세팅까지 해보았다.
오늘은 엔티티를 만들어 데이터를 어떻게 조회하는지 알아보자.
Entity
코드가 모여있는 곳에 entities 라는 폴더를 만든다.
그 폴더 내부에 ‘원하는이름.entity.ts’ 라는 파일을 만든다.
난 local.entity.ts 라는 지역 정보를 저장하기위한 엔티티 파일을 만들어보겠다.
import { Column, Entity, PrimaryGeneratedColumn } from ‘typeorm/index’;
@Entity(‘local_information’) //테이블이름
export class localEntity {
@PrimaryGeneratedColumn(‘increment’, { type: ‘bigint’ }) //기본키로 설정
id: number; //컬럼이름 : 컬럼 데이터타입@Column({ type: ‘bigint’ })
area_code: number;@Column({ length: 30 })
County: string;@Column({ length: 30 })
City: string;@Column({ type: ‘int’ })
grid_x: number;@Column({ type: ‘int’ })
grid_y: number;@Column({ type: ‘double’ })
longitude: number;@Column({ type: ‘double’ })
latitude: number;
}
위 코드처럼 자신이 필요한 컬럼과 타입 그리고 인덱스 설정을 적어서 만들면 된다.
데이터 조회
이제 만든 엔티티를 이용해 서비스레이어에서 데이터를 조회해보자.
서비스 레이어에 아래의 코드를 추가한다.
import { localEntity } from ‘src/entities/local.entity’;
import { InjectRepository } from ‘@nestjs/typeorm’;
…
@Injectable()
export class LocalService {
constructor(
@InJectRepository(localEntity)
private localRepository: Repository, ) { this.localRepository = localRepository; } }
위의 코드까지 추가하고 원하는 서비스레이어에 아래의 코드를 추가해서 실행해보자
this.localRepository.find();
위의 코드를 실행해 결과값을 출력해보면 해당 데이터베이스의 모든 데이터가 객체 형태로 넘어온 것을 알 수 있다.
마치며
오늘은 TypeORM을 통해 엔티티를 만들어보고 데이터를 조회해보았다.