본문 바로가기
NestJS

TypeORM - Repository 메서드 종류

by Programmer.Junny 2025. 2. 25.

TypeORM의 Repository는 엔티티와 관련된 CRUD 및 다양한 데이터베이스 조작 작업을 손쉽게 할 수 있도록 여러 메서드를 제공한다.

create

평범한 자바스크립트 객체를 엔티티 인스턴스로 변환한다.
주의: 실제 데이터베이스에 저장되지는 않고, 단지 객체를 생성하는 단계이다.

// DB에 저장하지 않고 인스턴스 생성
const user1 = this.userRepository.create({
email: 'test@test.com',
});

save

엔티티 인스턴스를 데이터베이스에 저장한다.
신규 생성 혹은 존재하는 엔티티의 업데이트 모두를 처리한다.

// 생성된 객체를 DB에 저장 (INSERT 또는 UPDATE)
const user2 = await this.userRepository.save({
email: 'test@test.com',
});

preload

주어진 조건(예: id)을 기반으로 기존 엔티티를 불러오고, 전달한 데이터를 병합한다.
주의: preload 자체는 저장하지 않으므로, 별도로 save를 호출해야 한다.

// id가 101인 엔티티를 불러와 전달한 값으로 덮어씌움 (아직 저장되진 않음)
const user3 = await this.userRepository.preload({
id: 101,
email: 'change@test.com',
});
// 이후에 user3를 저장하려면:
// await this.userRepository.save(user3);

update

특정 조건에 맞는 엔티티를 업데이트한다.
Entity 인스턴스를 로드하지 않고 직접 SQL UPDATE를 수행하기 때문에, 성능 측면에서 유리하다.

await this.userRepository.update({ id: 1 }, { email: 'updated@test.com' });

delete

조건에 맞는 엔티티를 데이터베이스에서 삭제한다
Entity 인스턴스를 먼저 로드하지 않고 삭제하기 때문에 효율적이다.

await this.userRepository.delete({ id: 101 });

increment, decrement

특정 컬럼의 값을 DB 레벨에서 직접 증가(increment)하거나 감소(decrement) 시킨다.
엔티티를 로드하지 않고 값만 변경하기 때문에 효율적이다.

// count 컬럼을 2 증가시킴
await this.userRepository.increment({ id: 1 }, 'count', 2);
// count 컬럼을 1 감소시킴
await this.userRepository.decrement({ id: 1 }, 'count', 1);

remove

이미 로드된 Entity 인스턴스를 데이터베이스에서 삭제한다.
엔티티가 존재하는지 검증된 상태라면 이 메서드를 사용할 수 있다.

const user = await this.userRepository.findOne({ where: { id: 101 } });
if(user) {
await this.userRepository.remove(user);
}

count

조건에 맞는 행의 개수를 조회한다.

const count = await this.userRepository.count({
where: { email: ILike('%0%') },
});

sum, average, minimum, maximum

특정 컬럼에 대한 합계, 평균, 최소값, 최대값을 계산한다.

const sum = await this.userRepository.sum('count', { id: LessThan(4) });
const average = await this.userRepository.average('count', { id: LessThan(4) });
const min = await this.userRepository.minimum('count', { id: LessThan(4) });
const max = await this.userRepository.maximum('count', { id: LessThan(4) });

find

여러 엔티티를 조건에 맞게 조회한다.

findOne

하나의 엔티티를 조건에 맞게 조회한다.

const users = await this.userRepository.find({ where: { isActive: true } });
const user = await this.userRepository.findOne({ where: { id: 1 } });

findOneOrFail

조회된 엔티티가 없으면 예외를 발생시킨다.

findAndCount

조건에 맞는 엔티티 배열과, 전체 행 개수를 함께 반환한다.
페이징 처리 시 유용하다.

const [users, count] = await this.userRepository.findAndCount({
take: 3,
});

query

복잡한 SQL 쿼리를 직접 실행할 수 있도록 한다.
SQL을 그대로 작성하여 결과를 얻을 수 있다.

const rawData = await this.userRepository.query('SELECT * FROM user WHERE email = ?', ['test@test.com']);

createQueryBuilder

보다 복잡한 쿼리를 빌더 패턴으로 작성할 수 있도록 지원한다.
동적 쿼리, JOIN, 그룹화, 집계 등 복잡한 조건을 손쉽게 구성할 수 있다.

const users = await this.userRepository
.createQueryBuilder('user')
.leftJoinAndSelect('user.profile', 'profile')
.where('user.isActive = :isActive', { isActive: true })
.orderBy('user.createdAt', 'DESC')
.getMany();

 

'NestJS' 카테고리의 다른 글

Authentication - Encryption (암호화)  (0) 2025.02.26
Authentication - JWT  (0) 2025.02.26
TypeORM - where 유틸리티  (0) 2025.02.25
TypeORM - FindManyOptions 파라미터  (0) 2025.02.24
TypeORM - 다대다 관계 구현  (0) 2025.02.24

최근댓글

최근글

skin by © 2024 ttuttak