select, where, order by 에서 사용 가능


H3-1. Simple Condition

@Test // Case Simple
public void testCaseSimple() {
    List<String> res = queryFactory
            .select(slave.age
                    .when(10).then("응애 🍼")
                    .when(20).then("응애! 👶🏻")
                    .when(30).then("응애애애애ㅐ액 👼🏻")
                    .otherwise("기타 🎸"))
            .from(slave)
            .fetch();

    System.out.println("⚠️⚠️⚠️⚠️ Case Simple Result: " + res);
}
⚠️⚠️⚠️⚠️ Case Simple Result: [응애 🍼, 응애! 👶🏻, 응애애애애ㅐ액 👼🏻, 기타 🎸]

H3-2. Complex Condition

CaseBuilder 사용 → when, then 사용하기 위해서


@Test // Case Complex
public void testCaseComplex() {
    List<String> res = queryFactory
            .select(new CaseBuilder()
                    .when(slave.age.between(10, 30)).then("응애 🍼")
                    .when(slave.age.between(31, 40)).then("응애애애애ㅐ액 🍼🍼")
                    .otherwise("기타 ??"))
            .from(slave)
            .fetch();

    System.out.println("⚠️⚠️⚠️⚠️ Case Simple Result: " + res);
}
⚠️⚠️⚠️⚠️ Case Simple Result: [응애 🍼, 응애 🍼, 응애 🍼, 응애애애애ㅐ액 🍼🍼]

H3-3. orderBy에서 Case 문 함께 사용

@Test // Case with orderBy
public void testCaseWithOrderBy() {
    NumberExpression<Integer> rankPath = new CaseBuilder()
            .when(slave.age.between(0, 20)).then(2)
            .when(slave.age.between(21, 30)).then(1)
            .otherwise(3);

    List<Tuple> tuples = queryFactory
            .select(slave.slaveName, slave.age, rankPath)
            .from(slave)
            .orderBy(rankPath.desc())
            .fetch();

    for (Tuple tuple : tuples) {
        String slaveName = tuple.get(slave.slaveName);
        Integer age = tuple.get(slave.age);
        Integer rank = tuple.get(rankPath);
        System.out.println("⚠️⚠️⚠️⚠️ Slave Name: " + slaveName + ", Age: " + age + ", Rank: " + rank);
    }
}
⚠️⚠️⚠️⚠️ Slave Name: slave4, Age: 40, Rank: 3
⚠️⚠️⚠️⚠️ Slave Name: slave1, Age: 10, Rank: 2
⚠️⚠️⚠️⚠️ Slave Name: slave2, Age: 20, Rank: 2
⚠️⚠️⚠️⚠️ Slave Name: slave3, Age: 30, Rank: 1