views:

44

answers:

2

Hi, I have a problem with Hibernate generating an SQL that do not work on SQLServer (works on PostgreSQL without any problems). I have tried to set the hibernate dialect for SQLServer but the same SQL is still generated and still do not work. The HQL query looks like this:

 select count(t) from ValidationLog t

The generated SQL looks like this:

 select count((vl.dataKey, vl.dataType)) from ValidationLog vl;

So my question is if there is anyway around it? Would really like to have the same code for both databases.

A: 

The HQL looks wrong to me, should be:

select count(t.dataKey) from ValidationLog t
Mark PM
No, it is a composite key in the table so there has to be at least two columns.
Peter Eriksson
What are you trying to count? The number of rows or distinct composite keys?
Mark PM
Number of rows in the tables is what I would like to count. Which should be the same as the number of distinct composite keys.
Peter Eriksson
In that case my answer still stands.
Mark PM
+1  A: 

According to the JPA specification, your JPQL query is perfectly valid:

4.8 SELECT Clause

...

The SELECT clause has the following syntax:

select_clause ::= SELECT [DISTINCT] select_expression {, select_expression}*
select_expression ::=
     single_valued_path_expression |
     aggregate_expression |
     identification_variable |
     OBJECT(identification_variable) |
     constructor_expression
constructor_expression ::=
     NEW constructor_name ( constructor_item {, constructor_item}*)
constructor_item ::= single_valued_path_expression | aggregate_expression
aggregate_expression ::=
     { AVG | MAX | MIN | SUM } ([DISTINCT] state_field_path_expression) |
     COUNT ([DISTINCT] identification_variable | state_field_path_expression |
          single_valued_association_path_expression)

However, you might be a victim of a bug reported in issues like HHH-4044, HHH-3096, HHH-2266 (or even HHH-5419).

Possible workaround: use a state_field_path_expression.

select count(t.someField) from ValidationLog t
Pascal Thivent
But it is not SQL that SQL Server would ever recognize as t-sql doesn't have that capability.
HLGEM
@HLGEM What SQL? The currently generated? If yes, then I agree it is incorrect, which is exactly the problem (according to the spec, the JPQL query from the OP is correct, it's up to the JPA provider to generate the appropriate SQL).
Pascal Thivent