1. JPQL 기본 함수

CONCAT, SUBSTRING, TRIM, LOWER, UPPER, LENGTH, LOCATE, ABS, SQRT, MOD, SIZE 등등 SQL문법 그대로 사용가능.

2. 사용자 정의 함수 호출

만약 사용자 정의 함수가 있다면 호출하는 방법은 다음과 같다.

1) 먼저 패키지를 하나 파고 사용자 정의 Dialect 클래스를 생성한다.

package dialect;

import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.type.StandardBasicTypes;

public class MyH2Dialect extends H2Dialect {
    public MyH2Dialect() {
        registerFunction("group_concat", new StandardSQLFunction("group_concat", StandardBasicTypes.STRING));
    }
}

이 코드 작성법을 외우긴 힘들고 상속시킨 H2Dialect로 들어가서 코드를 보면 저런식으로 구현이 되어있다. 긁어와서 정의된 함수 이름을 첫번째 파라미터와 StandardSQLFunction안의 첫번째 파라미터에 기재하면 된다.

2) Persistence.xml 수정

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
             xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
    <persistence-unit name="hello">
        <properties>
            <!-- 필수 속성 -->
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
            <property name="javax.persistence.jdbc.user" value="sa"/>
            <property name="javax.persistence.jdbc.password" value=""/>
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/~/test"/>
            <!-- <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>-->
            <property name="hibernate.dialect" value="dialect.MyH2Dialect"/>

            <!-- 옵션 -->
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.use_sql_comments" value="true"/>
            <property name="hibernate.jdbc.batch_size" value="10"/>
            <property name="hibernate.hbm2ddl.auto" value="create"/>
            <property name="hibernate.default_batch_fetch_size" value="100"/>
        </properties>
    </persistence-unit>
</persistence>

기존의 hibernate.dialect를 지우고 본인이 생성한 dialect 클래스를 기재하면 된다.

3) 사용 방법

String query1 = "select function('group_concat', m.username) from Member m ";
String query2 = "select group_concat(m.username) from Member m ";

List<String> result1 = em.createQuery(query1, String.class).getResultList();
List<String> result2 = em.createQuery(query2, String.class).getResultList();

두 쿼리 모두 정상 작동한다.