저장소(Repository)
저장소는 데이터베이스 CRUD 작업 시 사용하는 인터페이스를 의미합니다.
저장소는 동작시 구체적인 엔티티를 참조합니다.
CRUD란?
C; Create(insert)
R; Read(select)
U; Update(update)
D; Delete(delete)
저장소 사용 예시(NestJS)
기본적인 CRUD 예제
import { Injectable, NotFoundException } from '@nestjs/common';
import { Repository } from 'typeorm';
import { PostModel } from './entities/posts.entity';
import { InjectRepository } from '@nestjs/typeorm';
@Injectable()
export class PostsService {
constructor(
@InjectRepository(PostModel)
private readonly postRepository: Repository<PostModel>,
) {}
async getAllPosts(): Promise<PostModel[]> {
const posts = await this.postRepository.find();
return posts;
}
async getPostById(id: number): Promise<PostModel> {
const post = await this.postRepository.findOne({ where: { id } });
if (!post) throw new NotFoundException(`${id} 게시글은 존재하지 않습니다.`);
return post;
}
async createPost(body): Promise<PostModel> {
const { author, title, content } = body;
// create로 객체 생성
const post = this.postRepository.create({
author,
title,
content,
likeCount: 0,
comentCount: 0,
});
// save
const newPost = await this.postRepository.save(post);
return newPost;
}
async updatePost(id: number, body): Promise<PostModel> {
const { author, title, content } = body;
const post = await this.getPostById(id);
if (author) post.author = author;
if (title) post.title = title;
if (content) post.content = content;
const updatePost = await this.postRepository.save(post);
return updatePost;
}
async deletePost(id: number): Promise<void> {
const result = await this.postRepository.delete(id);
if(result.affected === 0){
throw new NotFoundException(`${id} 게시글은 존재하지 않습니다.`);
}
}
}
create() 메서드를 사용한 다음 save() 메서드를 사용하는 이유
create() 메서드는 단순히 인스턴스만 생성합니다.
save() 메서드만 사용해도 데이터베이스에 저장됩니다.
그런데 왜 create() 메서드를 사용한 다음 save() 메서드를 사용할까요?
create() 메서드를 사용하면 entity의 속성을 이용해 데이터 검증을 할 수 있기 때문입니다.
또한, create() 메서드를 사용하지 않으면 Entity Listeners가 실행되지 않습니다.
저장소 메서드
0.3.0 버전에서 findBy(), findOneBy() 메서드가 삭제되었습니다.
메서드 | 설명 |
create(객체) | 데이터베이스 테이블에 저장을 하지 않고, 객체만 생성. 오라클에서 commit을 안 한 것과 같습니다. |
save(객체) | 데이터베이스 테이블에 실제로 저장 |
insert(객체), update(객체) | 이 메서드들을 사용하면 Entity Listeners가 작동하지 않기 때문에 save() 메서드 사용을 권장합니다. |
preload(객체) | key를 사용해 조회. 나머지 입력 값은 해당 row 수정 하지만 저장은 X 오라클에서 commit을 안 한 것과 같습니. |
remove(객체), remove( [객체1, 객체2, ...] ) | 객체 삭제. Entity Listeners가 작동하고, 전달한 객체가 없으면 오류를 반환합니다. |
delete(key), delete(객체) | 조건에 따라 객체 삭제. Entity Listeners가 작동하지 않습니다. |
increment(객체, 컬럼명, 값) | 객체에 전달된 조건으로 조회 후 컬럼의 값을 전달한 값 만큼 증가 |
decrement(객체, 컬럼명, 값) | 객체에 전달된 조건으로 조회 후 컬럼의 값을 전달한 값 만큼 감소 |
count(객체) | 객체에 전달된 조건으로 조회 된 개수 |
sum(컬럼명, 객체) | 객체에 전달된 조건으로 조회된 모든 컬럼 값의 합 |
average(컬럼명, 객체) | 객체에 전달된 조건으로 조회된 모든 컬럼 값의 평균 |
minimum(컬럼명, 객체) | 객체에 전달된 조건으로 조회된 모든 컬럼 값의 최소값 |
maximum(컬럼명, 객체) | 객체에 전달된 조건으로 조회된 모든 컬럼 값의 최대값 |
find() | 조건 없이 모두 조회 |
find(객체) | 객체에 전달된 조건으로 조회 |
findOne(객체) | 객체에 전달된 조건으로 하나만 조회 |
fincAndCount(객체) | 객체에 전달된 조건으로 하나만 조회 및 count 반환 |
exist(객체) | 객체에 전달된 조건에 해당하는 값이 있으면 true 반환 |
find 메서드 옵션 객체 속성
find(), findOne(), findOneBy(), findAndCout() 메서드 사용 시 파라미터에 옵션 객체를 전달할 수 있습니다.
속성 | 설명 |
select | 조회할 컬럼 설정(false 지정해봐야 안 먹힘) |
where | 하나의 객체는 and 조건 배열에 여러 객체 전달 시 or 조건 |
order | 내림차순, 오름차순 지정 |
relations | 조인 관계 설정 |
skip | 처음 몇 개를 제외할지 결정(offset) |
take | 몇 개를 가져올지 결정(limit) 기본값 0: 모든 것을 가져옴 |
lock | lock 설정 findOne()에서만 사용 가능 |
예시
userRepository.find({
select: {
firstName: true,
lastName: true,
},
relations: {
profile: true,
photos: true,
videos: true,
},
where: {
firstName: "Timber",
lastName: "Saw",
profile: {
userName: "tshaw",
},
},
order: {
name: "ASC",
id: "DESC",
},
skip: 5,
take: 10,
lock: { mode: "optimistic", version: 1 },
})
where 옵션 객체 속성
where에 옵션 객체 전달 시 사용하는 속성들입니다.
속성 | 설명 |
not(n) | n이 아닌 것 sql의 not |
LessThan(n) | n보다 작은 것 |
LessThanOrEqual(n) | n과 같거나 n보다 작은 것 |
MoreThan(n) | n보다 큰 것 |
MoreThanOrEqual(n) | n과 같거나 n보다 큰 것 |
Equal(n) | n과 같은 것 |
Like(’%something%’) | something이 포함되는 것 |
ILike(’%something%’) | 대소문자 구분을 안하는 someghint이 포함되는 것 |
Beetween(a, b) | a <= 컬럼값 <= b |
In(a, b, c) | a, b, c 중 어떤 것이건 일치하는 컬럼 |
IsNull() | 비어 있는 것 |
Not(IsNull()) | 비어 있지 않은 것 |
'TypeORM' 카테고리의 다른 글
관계(Relation) (0) | 2025.05.07 |
---|---|
엔티티(Entity) (0) | 2025.05.04 |
TypeORM 환경 설정 (0) | 2025.05.04 |
TypeORM (0) | 2025.05.03 |