JAVA/JAVA__Interface-JPA

JPA에서 1:N JOIN 하기

말하는감자 2021. 3. 18. 22:01

JPA에서 1:N JOIN 하기

 

  • 휴대폰 테이블에는 휴대폰의 모델명이 들어있음
  • 휴대폰 디자인 테이블에는 휴대폰의 색상들이 들어있다
  • 각 휴대폰 모델별 색상을 조회하고 싶다
  • 휴대폰 모델명은 고유한 번호를 갖는다
select
s.color
from phone as p
inner join phone_design d on p.model_id = s.model_id
where p.phone_name = "아이폰";

Phone Entity

@Getter @Setter
@DynamicUpdate
@Entity(name="phone")
public class Phone {

    @OneToMany(mappedBy = "model_id")
    private List<PhoneDesign> phoneDesign

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id", updatable = false, nullable = false, insertable=false)
    private Long id;

    @Column(name="model_id")
    private Long modelId;

    @Column(name="phone_name")
    private String phoneName;
}

 

PhoneDesign Entity

@Getter @Setter
@DynamicUpdate
@Entity(name="phone_design")
public class PhoneDesign {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id", updatable = false, nullable = false, insertable=false)
    private Long id;

    @Column(name="model_id")
    private Long modelId;

    @Column(name="color")
    private String color;
}

 

컨트롤러


@RequiredArgsConstructor
@RestController
public class PhoneController {
    private final PhoneService phoneService;
    @GetMapping(value = "/phone/{phoneName}")
    public Map<String, Object> getPhoneColorByPhoneId(@PathVariable("phoneName") String phoneName) {
        Map<String, Object> res = new HashMapM<>();
        Phone phone = phoneService.findPhoneAndColorByPhoneName(phoneName);
        return res;
    }
}

서비스

@RequiredArgsConstructor
@Service
public class PhoneService {
    private final PhoneRepository phoneRepository;
    public Phone findPhoneAndColorByPhoneName(String phoneName) {
        return phoneRepository.findAllByPhoneName(phoneName)
    }
}

레파지토리

public interface PhoneRepository extends CrudRepository<Phone, Long> {
    @EntityGraph(attributePaths="phoneDesign")
    Phone findAllByPhoneName(String phoneName);
}

'JAVA > JAVA__Interface-JPA' 카테고리의 다른 글

cannot simultaneously fetch multiple bags - 1:N 다중 JOIN 도중 오류  (0) 2021.03.25
에러 모음  (0) 2021.03.22
JPA에서 1:N JOIN 하기  (0) 2021.03.18