내일배움캠프 TIL (230216): typeorm @primaryGeneratedColumn() vs. @PrimaryColumn()

Jiumn·2023년 2월 16일
0

entity class를 생성할 때는 반드시 primary key가 있어야 한다.

nestjs 강의 영상들 속에서 id의 데코레이터에 @PrimaryGeneratedColumn()을 부여하는 것을 보고 왜 @PrimaryColumn()이 아니라 @PrimaryGeneratedColumn()을 쓰는지 궁금해서 둘의 차이를 typeorm 공식문서에서 찾아봤다.

@PrimaryColumn() creates a primary column which takes any value of any type. You can specify the column type. If you don't specify a column type it will be inferred from the property type. The example below will create id with int as type which you must manually assign before save.

@primaryGeneratedColumn() creates a primary column which value will be automatically generated with an auto-increment value. It will create int column with auto-increment/serial/sequence/identity (depend on the database and configuration provided). You don't have to manually assign its value before save - value will be automatically generated.

둘의 가장 큰 차이는 auto-increment 여부다.
보통 id는 연속적인 값으로 자동적으로 숫자를 증가시켜주는 형태가 맞기 때문에 @primaryGeneratedColumn()를 사용한다.


@PrimaryColumn()으로 변경해도 적용이 되는지 확인해보니 에러가 발생했다.

QueryFailedError: ER_NO_DEFAULT_FOR_FIELD: Field 'id' doesn't have a default value

괄호 안에 다양한 인수를 넣어서 시도해봤지만 에러만 발생할 뿐 제대로 실행이 되지 않았다... 복세편살 @primaryGeneratedColumn() 사용하자.

profile
Back-End Wep Developer. 꾸준함이 능력이다.

0개의 댓글