데이터베이스의 상태를 변화시키기 위해 수행하는 작업 단위
하나의 트랜잭션이 성공적으로 끝났고, DB가 일관성있는 상태일 때 이를 알려주기 위해 사용하는 연산
하나의 트랜잭션 처리가 비정상적으로 종료되어 트랜잭션 원자성이 깨진 경우 즉, transaction이 정상적으로 종료되지 않았을 때, 트랜잭션이 시작되기 전 상태로 roll back해야 함
INSERT
INSERT
INSERT
+ 예제 INSERT
= 하나의 트랜잭션
둘 중 하나라도 (모종의 이유로) 실패하면 트랜잭션이 시작하기 전 상태로 돌려놓아야 함(Rollback)
Why? 원자성, 일관성이 깨진다.
// 실제 저희 service 코드 중 일부
@Injectable()
export class ProblemsService {
constructor(
// ...
@InjectDataSource() private dataSource: DataSource
) {}
async create(createProblemDTO: CreateProblemDTO, userId: number) {
await **this.dataSource.manager.transaction**(
async (transactionEntityManager: EntityManager) => {
const problem = this.problemRepository.create({
...createProblemDTO,
userId,
});
**const savedProblem = await transactionEntityManager.save(problem);**
const problemId = savedProblem.id;
for (const problemExample of createProblemDTO.examples) {
const example = this.exampleRepository.create({
problemId,
...problemExample,
});
**await transactionEntityManager.save(example);**
}
},
);
}
}