inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

실전! 스프링 데이터 JPA

연관관계가 있는 Entity 저장

1483

Ato
0

안녕하세요.

강의를 듣고 공부하는 중, 연관관계가 있는 Entity를 저장할 때 궁금한 부분이 있어 질문드립니다.

아래의 예제의 User에는 컬럼에 연관관계가 있는 UserType 엔티티가 있고,
화면에서는 typeCode값(UserType의 키값)과 userName값을 Dto로 전달받아서 저장을 하고있습니다.

User를 save할 때에 UserType을 조회 후 생성자로 객체를 만들고 save를 했었는데,
이렇게 하다보니 select insert 2개의 쿼리가 실행되더라구요.
(userTypeRepository.findById 후 save)

그래서 방법을 찾다보니 findById 대신에 getById로 UserType을 조회후 save하면,
UserType select가 Lazy로 동작하여 insert 쿼리만 실행이 되는걸 확인했습니다. (CASE1.)

또 다른방법으로 User 엔티티에 UserType의 키값인 typeCode를 추가하고,
dto에서 받은 typeCode로 User객체를 만들어 저장하는 방법도 있더라구요. (CASE2.)

JPA를 사용하면서 save시 getById로 호출후 save하는 방식이 맞는건지,
실무에서는 어떠한 방식으로 사용되는지 궁금하여 질문드립니다.

--------------------------

CASE 1.

@Entity  @Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class User {
     @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

    @OneToOne
    @JoinColumn(name = "TYPE_CODE")
    private UserType userType;

    @Column(name = "USER_NAME")
    private String userName;

public User(UserType userType, String userName) {
        this.userType = userType;
        this.userName = userName;        
    }
}

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class UserType {

    @Id
    @Column(name = "TYPE_CODE")
    private String typeCode;

    @Column(name = "TYPE_NAME")
    private String typeName;
}

@Getter
@Setter
public class UserFormDto {
    private String typeCode;
    private String userName;

    public User toEntity(UserType userType) {
        return new User(userType, userName);
    }    
}

 

@Service
...
@Transactional
public void createUser(UserFormDto userFormdto) {
UserType userType = userTypeRepository.getById(userFormdto.getTypeCode());
User user = userFormdto.toEntity(userType);
userRepository.save(user);
}

---------------------

CASE 2.

@Entity @Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class User {
@Id  @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

       @OneToOne
       @JoinColumn(name = "TYPE_CODE")
       private UserType userType;
      
       @Column(name = "TYPE_CODE")
        private String typeCode;

       @Column(name = "USER_NAME")
       private String userName;

public User(String typeCode, String userName) {
          this.typeCode = typeCode;
          this.userName = userName;        
       }
}

@Entity @Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class UserType {
    @Id
    @Column(name = "TYPE_CODE")
    private String typeCode;

    @Column(name = "TYPE_NAME")
    private String typeName;
}

 

@Getter
@Setter
public class UserFormDto {
    private String typeCode;
    private String userName;

    public User toEntity() {
        return new User(typeCode, userName);
    }    
}

 

@Service
...
@Transactional
public void createUser(UserFormDto userFormdto) {
User user = userFormdto.toEntity();
userRepository.save(user);
}

 

jpa

답변 1

1

김영한

안녕하세요. Ato님

다음을 참고해주세요.

https://www.inflearn.com/questions/204850

감사합니다.

스프링 백엔드 개발 로드맵

0

469

1

부트스트랩 유료화

1

440

2

H2 대신 mysql 등 다른 DB를 사용하시는 분들 중 Error creating bean with name 'entityManagerFactory' 에러가 나는 경우

0

432

0

강의 외 질문: 현시점의 querydsl (jOOQ vs Querydsl)

0

8583

2

jpql 무차별 사용에 대해

0

564

1

'스프링 완전 정복' 로드맵을 함께 위한 Java 지식의 정도

1

408

1

섹션 4 어떻게 변경할 것인가? 관련해서 질문드립니다

0

375

0

프로젝션 사용 이유

0

546

1

학습 방법

1

466

1

현재 공부방향이 괜찮은지 궁금합니다

1

563

1

강의 질문 드립니다.

0

575

1

데이터베이스 스키마에 대해 궁금한게 있어요

1

447

1