How to convert HQL to SQL Query programmatically (without logging)

后端 未结 7 1149
刺人心
刺人心 2021-02-05 12:10

I am executing the following HQL and it is executing properly

String hql = \"FROM Employee\";
Query query = session.createQuery(hql);
List results = query.list(         


        
7条回答
  •  清酒与你
    2021-02-05 12:54

    Hibernate Types

    Starting with the 2.9.11 version, the Hibernate Types open-source project offers the SQLExtractor utility that allows you to get the SQL query from any JPQL or Criteria API query, no matter you are using Hibernate 5.4, 5.3, 5.2, 5.1, 5.0, 4.3, 4.2, or 4.1.

    Get the SQL statement from a JPQL (HQL) Query

    Let's assume we have the following JPQL (HQL) query:

    Query jpql = entityManager.createQuery("""
        select 
           YEAR(p.createdOn) as year, 
           count(p) as postCount 
        from 
           Post p 
        group by 
           YEAR(p.createdOn)
        """, Tuple.class
    );
    

    With Hibernate Types, extracting the Hibernate-generated SQL query is as simple as that:

    String sql = SQLExtractor.from(jpql);
    

    And, if we log the extracted SQL query:

    LOGGER.info("""
        The JPQL query: [
            {}
        ]
        generates the following SQL query: [ 
            {}
        ]
        """,
        jpql.unwrap(org.hibernate.query.Query.class).getQueryString(),
        sql
    );
    

    We get the following output:

    - The JPQL query: [
        select    
            YEAR(p.createdOn) as year,    
            count(p) as postCount 
        from    
            Post p 
        group by    
            YEAR(p.createdOn)
    ]
    generates the following SQL query: [
        SELECT 
            extract(YEAR FROM sqlextract0_.created_on) AS col_0_0_,
            count(sqlextract0_.id) AS col_1_0_
        FROM 
            post p
        GROUP BY 
            extract(YEAR FROM p.created_on)
    ]
    

    Notice that we unwrapped the JPQL (HQL) Query to the Hibernate org.hibernate.query.Query interface which provided the getQueryString method we can use to log the associated JPQL query string.

提交回复
热议问题