Tips/Database, ORM

[TypeORM] Embedded Entity의 Column 이름 지정하기

dextto™ 2020. 5. 12. 22:58

TypeORM에는 Embedded Entity라는 개념이 있다.

여러 개의 엔티티에서 중복되는 컬럼들이 있을 때 이를 묶어서 별도의 엔티티(Embedded Entity)로 뽑아 내고,

뽑아낸 엔티티를 사용하고자 하는 엔티티에서 컬럼으로 선언하면 Embedded Entity에 선언된 컬럼들이 쭉 포함된다.

 

모두싸인 앱에는 User테이블과 InactiveUser라는 테이블이 있고, 두 테이블에는 모두 surveyXXXX 라는 필드들이 있다.

설문조사한 내용을 기록한 것인데, Inactive 상태로 바뀔 때 User 테이블에서 삭제하고 InactiveUser 테이블로 데이터를 복사한다.

 

이렇게 중복된 컬럼들을 Survey라는 Embedded Entity로 분리했다.

Survey.ts

export class Survey {
  @Column('varchar', { length: 60, nullable: true })
  public companyName: string | null;
  
  ...
}

 

User.ts

@Entity('User')
export class User {
...
  @Column(type => Survey)
  public survey: Survey;
...
}

 

그런데 이렇게 적용했더니, 컬럼이름이 기존 이름인 surveyCompanyName이 아니라, surveyCompanyname이 된다.

 

해결방안은 https://github.com/typeorm/typeorm/issues/4093#issuecomment-490638720을 참고했다.

Embedded Entity를 사용하는 엔티티에서 Column을 정의할 때 prefix 옵션을 false로 변경
User.ts

@Entity('User')
export class User {
...
  @Column(() => Survey, {
    prefix: false,
  })
  public survey: Survey;
...
}
Embedded Entity에서 이름을 직접 지정
Survey.ts

export class Survey {
  @Column('varchar', { length: 60, nullable: true, name: 'surveyCompanyName' })
  public companyName: string | null;
  
  ...
}

 

반응형