[JPA] null ์ฒ˜๋ฆฌ

JPA์—์„œ null์ฒ˜๋ฆฌ ํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด์„œ ์•Œ์•„ ๋ณด์ž.

Java8 Optional ์ฒ˜๋ฆฌ

    @Test
    public void nullTest() {
        Optional<Post> byId = postRepository.findById(1000l);
        System.out.println(byId);  // Optional.empty

        // assertj๋ฅผ ์‚ฌ์šฉ
        Assertions.assertThat(byId).isEmpty();
    }

JPA์—์„œ ๋‹จ์ผ ์—”ํ‹ฐํ‹ฐ๋ฅผ ์กฐํšŒํ•  ๋•Œ, Optional๊ฐ์ฒด๋ฅผ ๋ฆฌํ„ด ๋ฐ›๋„๋ก ์„ค์ •๋˜์–ด ์žˆ๋‹ค. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ์ดํ„ฐ๊ฐ€ ์—†๋Š” ๊ฐ’(์—ฌ๊ธฐ์—์„œ๋Š” id๊ฐ€ 1000)์„ ์กฐํšŒํ•˜๋ฉด nullPointerException์ด ๋‚˜์ง€ ์•Š๊ณ , Optional.empty๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค.

Collectio์—์„œ ๋นˆ ์ฝœ๋ ‰์…˜์„ ๋ฆฌํ„ดํ•จ (null ๋ฆฌํ„ดํ•˜์ง€ ์•Š์Œ)

    @Test
    public void nullTest() {
        List<Post> all = postRepository.findAll();
        System.out.println(all); // []
        Assert.assertNotNull(all);
    }

์—ญ์‹œ๋‚˜ ์•„๋ฌด๋Ÿฐ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†๋Š” Post๋ฆฌ์ŠคํŠธ๋ฅผ ์กฐํšŒํ–ˆ์„ ๋•Œ. null๊ฐ’์„ ๋ฆฌํ„ด ํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ, ๋น„์–ด์žˆ๋Š” Collection๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ฝ”๋“œ๋Š” ๋ถˆํ•„์š”ํ•˜๋‹ค.

public void someMethod(){
    List<Post> all = postRepository.findAll();
    // ๋ถˆํ•„์š”ํ•œ ์ฝ”๋“œ...........
    if (all == null){
        throw new Exception("exception ์ฒ˜๋ฆฌ")
    }
}

Spring 5.xx ๋Œ€ ๋ถ€ํ„ฐ๋Š” @Nullable, @NonNull ์ง€์›

์ฐธ๊ณ 

์—ฐ๊ด€ ํฌ์ŠคํŠธ