SQL subquery in Hibernate Query Language - java

I am new to HQL and I am working on subqueries.
I have the following SQL subquery:
select * from (
select * from table order by columnname
) as subquery
where columnvalue = 'somevalue';
I want to fire the query in HQL. I wrote the below code :
Result = session.createQuery("from (from table order by columnname) as subquery where columnvalue = :somevalue")
.setParameter(/*setting all parameters*/)
.list();
I am getting this exception:
QuerySyntaxException : unexpedted token :( line 1, column 10 [from (from ...)]
My SQL query is giving me correct results. How do I write it in HQL ?

I did not think HQL could do subqueries in the from clause
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-subqueries
note the sentence:
Note that HQL subqueries can occur only in the select or where clauses.
It will be better if you excute native SQL.

Related

Hibernate subquery problem with aggregate function

I'm trying to run this query within Hibernate (through JPA) but it throws
Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 32
Any way to make this work or make it better ? I would not want to use OR clause because the query is much slower when using that.
SELECT SUM(s) as sum FROM (
SELECT count (ID) AS s
FROM TABLE1 rr
WHERE rr.status = 0
AND (rr.risk = '1' AND rr.rate = '222' )
UNION ALL
SELECT count (ID) AS s
FROM TABLE1 rr
WHERE rr.status = 0
AND (rr.risk = '2' AND rr.open = '222' ))
With HQL queries, Hibernate ORM doesn't support subqueries in the FROM clause (you can use them in the WHERE clause).
If you cannot rewrite this query as HQL without the subquery (for performance reasons, for example), I think it's OK to run it on the db as a native SQL query:
String sqlQuery = ...;
session.createNativeQuery(sqlQuery).getSingleResult();

Convert sql query to hql

SELECT recipe.name,SUM(salesdetails.quantity::integer),recipe.price As Quantity
FROM (salesinfo JOIN salesdetails ON salesinfo.sessionid=salesdetails.salesinfo_sessionid)
JOIN recipe ON salesdetails.recipe_id=recipe.id group by salesdetails.recipe_id,recipe.name,recipe.price
ORDER BY SUM(salesdetails.quantity::integer) DESC;
Can anyone give me the hql query for this?
If you are not acquainted with the HQL and want to use the same query ,then you can do it using the native query feature of the Hibernate like this :
#QUERY(value="SELECT recipe.name, SUM(salesdetails.quantity::
INTEGER),recipe.price AS Quantity
FROM (salesinfo
JOIN salesdetails ON salesinfo.sessionid=salesdetails.salesinfo_sessionid)
JOIN recipe ON salesdetails.recipe_id=recipe.id
GROUP BY salesdetails.recipe_id,recipe.name,recipe.price
ORDER BY SUM(salesdetails.quantity:: INTEGER) DESC", nativeQuery = TRUE)
But I would recommend that you first try to convert the same in into HQL query and then if any issue then you should ask it here instead of directly asking for the converted query. Meanwhile this can help.

Hibernate 2 with MSSQL for ORDER BY

I have been working with Oracle and Postgre and recently switched to MS SQL 2012.
I use hibernate in my application and wherever I have used the Order by Criteria:
(criteria.addOrder(Order.asc("applicationId")));
It causes an error saying:
aggregate functions dont work.
Once I comment that line out my program works and data can be retrieved.
I'm using Hibernate 3.
Is there any way to order it through hibernate without this error?
edit..
This is one error I get,
Column "SKY.tcrent.RENTNO" is invalid in the ORDER BY clause because
it is not contained in either an aggregate function or the GROUP BY
clause.
Edit 2..
MY query
Query tcSchaduleQ = getSession().createQuery("SELECT SUM(tcs.dueAmount) FROM TrialCalculationSchedule tcs WHERE tcs.facilityId=:facilityId AND tcs.rentalNumber>:rentalNumber AND tcs.dueDate>:dueDate AND dueTypeId IN(:dueTypeId) ORDER BY tcs.rentalNumber ").setInteger("rentalNumber", facility.getPeriod() - noOfprePayments).setInteger("facilityId",facility.getFacilityId()).setDate("dueDate", date).setParameterList("dueTypeId", plist);
Number tcsAmt = (Number) tcSchaduleQ.uniqueResult();
and this is what hibernate generates in HQL
SELECT
SUM(tcs.dueAmount)
FROM
TrialCalculationSchedule tcs
WHERE
tcs.facilityId=:facilityId
AND tcs.rentalNumber>:rentalNumber
AND tcs.dueDate>:dueDate
AND dueTypeId IN(
:dueTypeId
)
ORDER BY
tcs.rentalNumber
and this is the SQL
select
SUM(trialcalcu0_.DUEAMT) as col_0_0_
from
SKYBANKSLFHP.tcrent trialcalcu0_
where
trialcalcu0_.FACID=?
and trialcalcu0_.RENTNO>?
and trialcalcu0_.DUEDATE>?
and (
trialcalcu0_.DUETYPEID in (
? , ?
)
)
order by
trialcalcu0_.RENTNO
Look Like you mix aggregate and non-aggregate expressions .If you are using any aggregate function like AVG() in Select query with some other non-aggregate then you must use Group By ..
Try something like this
createQuery("SELECT SUM(tcs.dueAmount) As DueAmount ...
If you are using Criteria then it should be like this
Criteria crit = sess.createCriteria(Insurance.class);
ProjectionList proList = Projections.projectionList();
proList.add(Projections.sum("investementAmount"));
crit.setProjection(proList);
List sumResult = crit.list();

Projections.countDistinct with Hibernate produces unexpected result

I have the following code
Criteria criteria = this.getCriteriaForClass(DeviceListItem.class);
Projection rowCountProjection = Projections.countDistinct("color");
criteria.setProjection(rowCountProjection);
int rowCount = ((Long) criteria.uniqueResult()).intValue();
return rowCount;
, whose purpose is to find out the number of rows with different values for the field named "color". The problem is that
Projections.countDistinct("color");
returns the same number of results as
Projections.count("color");
even though there are multiple rows with same color in the database view. When converting the Criteria object to SQL, I see that the SQL produced by Hibernate is
select count(this_.COLOR) as y0_ from DEVICESLIST_VIEW this_ where 1=1
when I would expect it to be
select count(distinct this_.COLOR) as y0_ from DEVICESLIST_VIEW this_ where 1=1
Why doesn't it work like expected and is there some remedy? Unfortunately I have no option to use HQL in this case.
It's a bug, fixed in 3.5.2: HHH-4957.

Hibernate SQL to HQL

Im running into some problems when trying to convert a SQL query into HQL (or Criteria/Restriction). I have the following SQL query:
Select count(n), CreatedDate from (
Select count(serverId) as n, Date(Created) as CreatedDate
from mytable
group by Date(Created), serverId
) as tbl
group by CreatedDate;
So what is the HQL (or Criteria) equivalent?
Some SQL queries cannot be directly translated to HSQL but this might help: HQL Subqueries in joins

Categories