본문 바로가기
개발/Database

[JPA] @ElementCollection 어노테이션

by yo.na 2023. 7. 1.

✔ 개념

RDB 는 Collection 형태의 데이터를 저장할 수 없다. 따라서 컬렉션을 저장하기 위해서는 별도의 테이블을 만들어서 따로 관리해줘야한다. Jpa 에서는 @ElementCollection 을 사용하여 해당 컬럼이 컬렉션 객체임을 알려줄 수 있다.

값 타입 컬렉션은 개념적으로 보면 1:N 관계이다.

 

✔사용방법

@Entity
class Test {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO )
  val id: Long = 0

  @Column
  @ElementCollection
  var roles: List<String> = ArrayList();

}

roles 컬럼이 권한 여러개를 가질 경우 ElementCollection 어노테이션을 사용해서 별도의 테이블로 관리할 수 있다.

 

@Repository
interface TestRepository: JpaRepository<Test, Long> {
}

 

entity, repository 정의 후 실행시키면 아래와 같이 test 테이블과 test_roles 테이블을 별도로 생성하는 것을 확인할 수 있다.

Hibernate: 
    
    create table test (
        primary key (id)
    ) engine=InnoDB
Hibernate: 
    
    create table test_roles (
       test_id bigint not null,
        roles varchar(255)
    ) engine=InnoDB
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: 
    
    alter table test_roles 
       add constraint FKtdd77sjlq0vgptby10j7eamqa 
       foreign key (test_id) 
       references test (id)

생성된 테이블 확인!

 

 

 

✔참고

https://ttl-blog.tistory.com/121