repository
import java.util.List;
public interface ProductInfoRepository {
List<ProductInfoResult> findProductInfoWithGroup(String columnName, String factoryCode);
}
@Repository
@RequiredArgsConstructor
public class ProductInfoCustomRepository implements ProductInfoRepository {
private final JPAQueryFactory queryFactory;
private final QProductInfo qProductInfo;
public List<ProductInfoResult> findProductInfoWithGroup(String columnName, String factoryCode) {
CaseBuilder caseBuilder = new CaseBuilder();
StringPath attributeA = createDynamicColumn(columnName);
BigDecimal threshold80 = Expressions.numberTemplate("{0} + {1} * 0.8", attributeA, subQuery().diff);
BigDecimal threshold60 = Expressions.numberTemplate("{0} + {1} * 0.6", attributeA, subQuery().diff);
BigDecimal threshold40 = Expressions.numberTemplate("{0} + {1} * 0.4", attributeA, subQuery().diff);
BigDecimal threshold20 = Expressions.numberTemplate("{0} + {1} * 0.2", attributeA, subQuery().diff);
return queryFactory
.select(
qProductInfo.productQuantity.as("productQuantity"),
attributeA.eq(columnName).as("attributeA"),
caseBuilder
.when(attributeA.goe(threshold80)).then("A")
.when(attributeA.lt(threshold80).and(attributeA.goe(threshold60))).then("B")
.when(attributeA.lt(threshold60).and(attributeA.goe(threshold40))).then("C")
.when(attributeA.lt(threshold40).and(attributeA.goe(threshold20))).then("D")
.otherwise("E").as("groupName")
)
.from(qProductInfo, subQuery())
.where(qProductInfo.processCode.eq(factoryCode).and(attributeA.isNotNull()))
.fetch();
}
private QProductInfo subQuery() {
QProductInfo subQuery = new QProductInfo("sub_query");
return subQuery;
}
private StringPath createDynamicColumn(String columnName) {
switch (columnName) {
case "column4":
return QProductInfo.column4;
case "column5":
return QProductInfo.column5;
case "column6":
return QProductInfo.column6;
default:
throw new IllegalArgumentException("[FAIL] 지원하지않는컬럼 " + columnName);
}
}
}