JPA 기초 - 값 컬렉션 List 매핑

2024. 1. 18. 17:15·JPA
본 내용은 유튜브 최범균님의 강의 내용을 정리한 내용입니다.
JPA 기초 09 값 콜렉션 List 매핑

컬렉션 List 타입 필드 매핑

package com.example.jpa.entity;

...

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "question")
public class Question {
    @Id
    private String id;
    private String text;

    @ElementCollection
    @CollectionTable(
            name = "question_choice",
            joinColumns = @JoinColumn(name = "question_id")
    )
    @OrderColumn(name = "idx") // 인덱스 값 컬럼 지정
    @Column(name = "text")
    private List<String> choices;
}
  • List 타입의 choices 필드를 매핑하는 예시입니다.
  • @OrderColumn 어노테이션은 List의 순서(INDEX)를 저장할 컬럼을 지정할 때 사용합니다.

엔티티 객체 저장

Question question = new Question("Q1", "질문", List.of("보기1", "보기2"));
entityManager.persist(question);
  • List 타입의 값을 저장할 때 INDEX 값도 같이 저장합니다.

데이터베이스 조회

엔티티 객체 조회(Lazy, Eager)

Question foundQuestion = entityManager.find(Question.class, question.getId());
System.out.println("보기 개수: " + foundQuestion.getChoices().size());
  • Lazy일 경우에는 foundQuestion.getChoices() 실행시 SELECT 쿼리가 따로 진행되고 Eager일 경우에는 LEFTJOIN을 사용하여 한번에 조회합니다.

List 수정 - 새로 할당

Question foundQuestion = entityManager.find(Question.class, question.getId());
foundQuestion.setChoices(List.of("보기3", "보기4"));
  • DELETE 쿼리를 실행하여 기존의 choices 값들을 삭제 후 새로운 값을 INSERT 합니다.

엔티티 객체 삭제

Question foundQuestion = entityManager.find(Question.class, question.getId());
entityManager.remove(foundQuestion);
  • JPA 생성 쿼리
Hibernate: 
    delete from question_choice where question_id=?
Hibernate: 
    delete from question where id=?
  • Question 객체를 삭제하는 경우 해당 객체와 연관된 데이터가 모두 삭제됩니다.

@Embeddable 타입 List 매핑 설정

package com.example.jpa.entity;

...

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "question")
public class Question {
    @Id
    private String id;
    private String text;

    @ElementCollection
    @CollectionTable(
            name = "question_choice",
            joinColumns = @JoinColumn(name = "question_id")
    )
    @OrderColumn(name = "idx") // 인덱스 값 컬럼 지정
    private List<Choice> choices; // List 제네릭 타입 Choice로 변경
}
  • List의 제네릭 타입을 @Embeddable 클래스 타입으로 변경합니다.
package com.example.jpa.entity;

...

@Data
@NoArgsConstructor
@AllArgsConstructor
@Embeddable
public class Choice {
    private String text;
    private boolean input;
}

'JPA' 카테고리의 다른 글

JPA 기초 1 - 1 단방향 연관 관계  (0) 2024.01.19
JPA 기초 - 값 컬렉션 Map 매핑  (0) 2024.01.18
JPA 기초 - 값 컬렉션 Set 매핑  (0) 2024.01.18
JPA 기초 - @Embeddable을 사용하여 다른 테이블 매핑하기  (0) 2024.01.17
JPA 기초 - @Embeddable  (0) 2024.01.17
'JPA' 카테고리의 다른 글
  • JPA 기초 1 - 1 단방향 연관 관계
  • JPA 기초 - 값 컬렉션 Map 매핑
  • JPA 기초 - 값 컬렉션 Set 매핑
  • JPA 기초 - @Embeddable을 사용하여 다른 테이블 매핑하기
PortLee
PortLee
  • PortLee
    프로그래밍 공부
    PortLee
  • 전체
    오늘
    어제
    • 분류 전체보기
      • C++
      • JAVA
      • JPA
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Entity 연관관계
    컬랙션 매핑
    컬렉션 매핑
    entity mapping
    map
    @Basic
    @Embeddable
    1-1연관관계
    MemberEntity
    @CollectionTable
    SQL Mapping
    JPA
    @Access
    Table 기본키 생성 전략
    Entity
    다른 테이블 매핑
    기본키 매핑
    allocationSize
    MemberService
    @AttributeOverride
    MemberRepository
    식별자공유
    JoinColumn
    set
    필드와 컬럼 매핑
    1-N
    Translent
    persistence.xml
    @Table
    list
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
PortLee
JPA 기초 - 값 컬렉션 List 매핑
상단으로

티스토리툴바