Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Spring
- 자료구조
- 개발자 취업
- 코딩공부
- 배열
- 이진 탐색(binary search)
- 코딩
- Entity
- 코딩문제
- 면접(java
- ArrayList
- css
- Java
- 99클럽
- 항해99
- HTML
- github
- Til
- GIT
- aop
- 정렬 알고리즘(sort algorithm)
- wil
- CS
- Grafana
- 자바
- 프로그래머스
- 코딩테스트 준비
- cs 공부)준비
- 메서드
- 회고
Archives
- Today
- Total
hayu's 개발 일지
[TIL]240316 트러블 슈팅: 아이디 값 null 본문
- 문제
엔티티 연관매핑 후 코드 실행했는데 테이블에 연관된 엔티티의 아이디값이 들어가지 않고 null이 나오는 문제.
- 원인
아직 모르겠다. 엔티티 연관관계도 확인했는데 서비스 코드에서 choice에 게임 아이디 주입 코드가 필요한 것 같다.
/*
* 밸런스 게임 생성*/
@Transactional
public GameResponseDto createGame(GameRequestDto gameRequestDto, UserDetails userDetails) {
User user = userRepository.findByEmail(userDetails.getUsername())
.orElseThrow(()->new CustomApiException("사용자를 찾을 수 없습니다."));
/*
* 선택지 생성*/
Choice choiceA = Choice.builder()
.content(gameRequestDto.getChoiceA())
.build();
Choice choiceB = Choice.builder()
.content(gameRequestDto.getChoiceB())
.build();
choiceRepository.save(choiceA);
choiceRepository.save(choiceB);
/*builder 를 사용해서 객체 생성 */
Game game = Game.builder()
.gameTitle(gameRequestDto.getGameTitle())
.user(user)
.choices(Arrays.asList(choiceA,choiceB))
.build();
gameRepository.save(game);
return GameResponseDto.builder()
.id(game.getId())
.username(user.getUsername())
.gameTitle(game.getGameTitle())
.choiceA(choiceA.getContent())
.choiceB(choiceB.getContent())
.build();
}
- 해결방안
choice 객체를 생성할 때 game 의 값을 넣어줬다.
/*
* 밸런스 게임 생성*/
@Transactional
public GameResponseDto createGame(GameRequestDto gameRequestDto, UserDetails userDetails) {
User user = userRepository.findByEmail(userDetails.getUsername())
.orElseThrow(() -> new CustomApiException("사용자를 찾을 수 없습니다."));
/*builder 를 사용해서 객체 생성 */
Game game = Game.builder()
.gameTitle(gameRequestDto.getGameTitle())
.user(user)
.build();
gameRepository.save(game);
/*
* 선택지 생성*/
Choice choiceA = Choice.builder()
.content(gameRequestDto.getChoiceA())
.game(game)
.build();
Choice choiceB = Choice.builder()
.content(gameRequestDto.getChoiceB())
.game(game)
.build();
choiceRepository.save(choiceA);
choiceRepository.save(choiceB);
return GameResponseDto.builder()
.id(game.getId())
.username(user.getUsername())
.gameTitle(game.getGameTitle())
.choiceA(choiceA.getContent())
.choiceB(choiceB.getContent())
.build();
}
'프레임워크 > spring' 카테고리의 다른 글
[TIL]240320 엔티티(Entity) 연관관계 매핑(1) (0) | 2024.03.20 |
---|---|
[TIL]240319 Entity & DTO (0) | 2024.03.19 |
[TIL]240314 Swagger (1) | 2024.03.14 |
[TIL]240313 Builder Pattern (0) | 2024.03.13 |
[TIL]240312 트랜잭션(transaction) (0) | 2024.03.12 |