ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JPA์˜ Cross Join ๊ฐœ์„ ํ•˜๊ธฐ
    Back-end/TIL 2022. 4. 20. 09:29

    ๐Ÿ“Œ ์ƒํ™ฉ

    ์•„๋ž˜ ์˜ˆ์‹œ ์ฝ”๋“œ์—์„œ PharmacyEmployee ์—”ํ‹ฐํ‹ฐ๋Š” Pharamcy, PharmacyEmpUser ์—”ํ‹ฐํ‹ฐ์™€ ๊ฐ๊ฐ N:1 ๊ด€๊ณ„์ด๋‹ค.

    ์•„๋ž˜์™€ ๊ฐ™์ด JPQL ์ž‘์„ฑ์‹œ Join์„ ๋ช…์‹œํ•˜์ง€ ์•Š์•˜๋‹ค. 

    public interface PharmacyEmployeeRepository extends JpaRepository<PharmacyEmployee, Long> {
    
        @Query("select pe.id as id, " +
                "pe.pharmacy.pharmacyName as pharmacyName, " +
                "pe.pharmacyEmpUser.email as email, " +
                "pe.pharmacyEmpUser.name as name " +
                "from PharmacyEmployee pe " +
                "where pe.pharmacy.id = :pharmacyId")
        List<PharmEmployeeDspResultDtoVo> findAllByPharmacyId(@Param("pharmacyId") Long pharmacyId);
    }

     

    โ–ถ๏ธ ์‹คํ–‰ ์ฟผ๋ฆฌ ํ™•์ธ

    ์‹คํ–‰ ์ฟผ๋ฆฌ

    ์‹คํ–‰ ์ฟผ๋ฆฌ๋ฅผ ํ™•์ธํ•ด๋ณด๋‹ˆ ์œ„์™€ ๊ฐ™์ด Pharmacy์™€ PharmacyEmpUser์— ๋Œ€ํ•ด Cross Join์„ ํ•ด์„œ ๊ฐ’์„ ์กฐํšŒํ•œ๋‹ค.

     

    ์ฆ‰, PharmacyEmployee์˜ ๋ฐ์ดํ„ฐ ๊ฐœ์ˆ˜ X Pharmacy์˜ ๋ฐ์ดํ„ฐ ๊ฐœ์ˆ˜ X PharmacyEmpUser์˜ ๋ฐ์ดํ„ฐ ๊ฐœ์ˆ˜๋ฅผ ํ•œ ๋ชจ๋“  ๊ฒฝ์šฐ์— ๋Œ€ํ•œ row์„ ์ƒ์„ฑํ•œ ๋’ค, where์ ˆ์˜ ์กฐ๊ฑด์— ํ•ด๋‹นํ•˜๋Š” row๋งŒ ๋ฐ˜ํ™˜ํ•˜๊ฒŒ ๋˜๋Š” ๊ฒƒ์ด๋‹ค. (Cross Join์ด ๋ฌธ์ œ๊ฐ€ ๋˜๋Š” ์ด์œ )

     

    ๐Ÿ“Œ ์›์ธ

    • JPQL์˜ ๋‚ด๋ถ€ ๊ตฌํ˜„์ฒด๋กœ ์‚ฌ์šฉํ•œ Hibernate๋Š” JPQL ์ž‘์„ฑ์‹œ Join์„ ๋ช…์‹œํ•˜์ง€ ์•Š์€ ์•”๋ฌต์ ์ธ Join์„ ํ•  ๊ฒฝ์šฐ Cross Join์„ ์‚ฌ์šฉํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ์œ„์™€ ๊ฐ™์ด Join์„ ๋ช…์‹œํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ Cross Join์„ ์ˆ˜ํ–‰ํ•œ ๊ฒƒ์ด๋‹ค.

     

    ๐Ÿ“Œ ๊ฐœ์„ 

    • ๊ธฐ์กด์˜ ์•”๋ฌต์  Join ๋Œ€์‹  JPQL ์ž‘์„ฑ์‹œ Join์„ ๋ช…์‹œํ•ด์ค€๋‹ค.
    @Query("select pe.id as id, " +
                "p.pharmacyName as pharmacyName, " +
                "peu.email as email, " +
                "peu.name as name " +
                "from PharmacyEmployee pe " +
                "join pe.pharmacy p " +	//Join์„ ๋ช…์‹œํ•จ
                "join pe.pharmacyEmpUser peu " +	//Join์„ ๋ช…์‹œํ•จ
                "where p.id = :pharmacyId")
    List<PharmEmployeeDspResultDtoVo> findAllByPharmacyId(@Param("pharmacyId") Long pharmacyId);

    ์‹คํ–‰ ์ฟผ๋ฆฌ

    ์‹คํ–‰๋œ ์ฟผ๋ฆฌ๋ฅผ ๋ณด๋ฉด Cross Join์ด ์•„๋‹Œ Inner Join์„ ์ˆ˜ํ–‰ํ•œ๋‹ค.

     

    ๐Ÿ“Œ ์ถ”๊ฐ€ ๊ฐœ๋… ์ •๋ฆฌ

    Cross Join ์ด๋ž€?

    • ์ง‘ํ•ฉ์—์„œ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ๊ฒฝ์šฐ์ด๋‹ค.
    • ์˜ˆ๋ฅผ ๋“ค์–ด, A ์ง‘ํ•ฉ = {a, b}์™€ B ์ง‘ํ•ฉ = {1, 2, 3}์ด๋ฉด, ์ด๋“ค์˜ Cross Join์€ AXB๋กœ {(a,1), (a,2), (a,3), (b,1), (b,2), (b,3)}์ด ๋œ๋‹ค. ๋ชจ๋“  ๊ฒฝ์šฐ์— ๋Œ€ํ•ด ๋‚˜์˜ค๋ฏ€๋กœ ์ผ๋ฐ˜์ ์ธ Join๋ณด๋‹ค ์„ฑ๋Šฅ์ƒ ์ด์Šˆ๊ฐ€ ๋ฐœ์ƒํ•˜๊ฒŒ ๋œ๋‹ค.

     

    ๐Ÿ“Œ ๊ฐ„๋‹จ ๋Š๋‚€์ 

    repository ๋‹จ์œ„ ํ…Œ์ŠคํŠธ๋ฅผ ์ˆ˜ํ–‰ํ•ด ์‹คํ–‰ ์ฟผ๋ฆฌ๋ฅผ ํ™•์ธํ•˜์ง€ ์•Š์•˜๋‹ค๋ฉด ๋†“์น ๋ป”ํ•œ ๋‚ด์šฉ์ด์—ˆ๋‹ค.

    ํ…Œ์ŠคํŠธ์˜ ์ค‘์š”์„ฑ์„ ๋‹ค์‹œํ•œ๋ฒˆ ๊นจ๋‹ซ๊ฒŒ ๋˜์—ˆ๋‹ค.

     

     

    ๐ŸŽˆ์ฐธ๊ณ 

    https://jojoldu.tistory.com/533

     

    ๋Œ“๊ธ€

Designed by Tistory.