BE

[TypeORM] Repository insert 과 save 의 차이

앤오엔 2023. 7. 22. 07:53

TypeORM 을 사용해서 특정 데이터를 삽입할 때 주로 create 로 객체를 만들고 save로 저장하는 로직을 쓰곤 했다.

그러나, 회사에서 insert를 쓰는 게 더 낫지 않냐라는 이야기가 나왔고 그 둘의 차이를 비교해보았다.

 

 

 

공통점

insert과 save 메소드 모두 데이터베이스에서 엔티티를 생성하는데 사용한다.

 

 

 

차이점

두 메소드의 차이점은 엔티티의 존재 여부에 따라 다른 동작을 한다는 것과 반환 값에 있다.

 

 

save

생성한 엔티티가 있다면 새로 삽입한다.

그러나, 이미 존재한다면 기존 엔티티의 데이터를 업데이트 한다.

즉, insert()와 update()의 기능을 한 번에 적용한다.

생성한 엔티티를 반환한다.

 

Argument : entity | entity[]

Return : the saved entity | entities

 

 

insert

생성한 엔티티의 존재 여부 상관없이 무조건 새로 생성한다.

반환값은 없다.

 

Argument : entity | entity[]

Return : the saved entity | entities

 

 

 

예제

// save

const post = this.postRepository.create({
    title: "New Post",
    content: "This is a best contents",
});
const result = await this.postRepository.save(post);

console.log(result); // the saved post entity

 

// insert

const post = this.postRepository.create({
    title: "New Post",
    content: "This is a best contents",
});
await this.postRepository.insert(post);

 

 

 

참고자료

https://dev.to/rishit/optimizing-typeorm-tips-from-experience-part-1-dont-use-save-4ke9

https://typeorm.io/repository-api