Alessandro
Alessandro

Reputation: 4472

Getting SQL from Criteria

I'm working with hibnernate and I've a piece of code like:

    Criteria criteria = getCurrentSession().createCriteria(objectClass);
    criteria.add(Restrictions.isNull("myFields"));
    System.out.println("SQL: " + criteria.getSQL()); <-- How can I do this?
    return criteria.list();

I'd like to print the SQL (or HQL) to the console, for debugging, but I can't find any method to get this kind of information.

I've already seen many answers on stackoverflow like this and this but those are old questions and I dosen't find any useful answer.

Can anyone help me? Thanks

Upvotes: 0

Views: 3392

Answers (2)

Kirill Dmitriev
Kirill Dmitriev

Reputation: 116

The easiest way to do this -- edit your Hibernate configuration.

You can set up

hibernate.show_sql = true

to enable the logging of all the generated SQL statements to the console.

Moreover you can set up

hibernate.format_sql = true
hibernate.use_sql_comments = true

to make it more readable

Read more about Hibernate configuration here

Upvotes: 4

Piotr Rogowski
Piotr Rogowski

Reputation: 3890

if you use persistance.xml then you add property

<property name="hibernate.show_sql" value="true"/>

Upvotes: 2

Related Questions