Martin Irigaray
Martin Irigaray

Reputation: 675

Hibernate HQL Count and Implicit Join result are different

I have Class A with fields

Long id
B activity

And related class B

Long id
String name

Then I have the HQL query:

select a.id, a.activity.name from A a;

Some B fields on class A have null values, so left join gives more results than inner join.

I'm generating automatically the HQL, so I want the select and then the count:

select count(*) from A;

This gives me different results.

Is some way to resolve this, other than adding the explicit left join on the SQL (I'm receiving the HQL, can't change it).

Upvotes: 3

Views: 783

Answers (1)

Carlos Laspina
Carlos Laspina

Reputation: 2231

Try execute the count with the same query, this way:

Query query = getEm().createQuery("select a.id, a.activity.name from A a");

int count = query.getResultList().size();

Or if you want to create a native query, configure your persistence.xml to enable log statement. So you can modify the original select to make the count. Statement logging and statistics

  • hibernate.show_sql
  • hibernate.format_sql
  • hibernate.use_sql_comments

    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
        <property name="show_sql" value="true" />
        <property name="format_sql" value="true" />
        <property name="hibernate.hbm2ddl.auto" value="update" />
    </properties>
    

Upvotes: 0

Related Questions