This is HQL query :
SELECT COUNT(s)
FROM Site s JOIN s.topics t
INNER JOIN t.topicExpertAssignment tea
INNER JOIN tea.expert u
INNER JOIN u.userinfo info
WHERE tea.assignedBy.id = 1 AND s.createdBy = tea.expert.id
ORDER BY s.name
when i try to run this HQL query first time , it Generate org.hibernate.exception.SQLGrammerException: could not execute query exception and when i try to run again this query it generates org.hibernate.exception.GenericJDBCEXception: could not execute query exception. without COUNT() the query run successfully. how to resolve this exceptions and thanks in Advance.
Query is incorrect, because ORDER BY references to s.name, and s.name is not one of the items in select list.
Most likely correct solution is to remove ORDER BY s.name. It does not make too much sense to define order when result is one value.
Related
We have a HQL SELECT query that, as a result, returns Java objects. To our surprise, some objects are missing in the result list.
I've checked the db for one of the missing objects and could not find a problem. Furthermore, I set a break point in the constructor of 'ParsableObject' that watches for the values of the missing object and it is triggers. But yet, that object is not in the result list.
The result contains some other objects and there is no exception thrown. Are there any known issues that I should look out for?
What I did not do yet: Check the logs of hibernate. I've set hibernate.show_sql to true but did not get a log. But that's a different issue.
The prepared query:
<query name="ObjectDAOHibernate.getSessionObjects">
<query-param name="idSession" type="long"/>
<![CDATA[
select new de.smartshift.ucchecker.model.ParsableObject(
to.idObject, to.objectName, to.description,
tom.codeSize, tom.codeSizeModified,
tom.lineCount, tom.normalizedLineCount, tom.commentLineCount, tom.lineCountModified,
tot.objectTypeCode,
ocst.idObjectState,
odst.idObjectState,
opst.idObjectState,
otst.idObjectState,
oust.idObjectState,
sapr3data.devClass,
to.standard,
to.tblFolder.relevant)
from
de.smartshift.ucchecker.db.hib.TblObject to join to.tblFolder tf
join tf.tblSession ts
join to.tblObjectType tot
join to.tblObjectMetadata tom
join to.tblObjectProcessingState tops
join tops.tblObjectStateByRefidCustomerState ocst
join tops.tblObjectStateByRefidDownloadState odst
join tops.tblObjectStateByRefidParserState opst
join tops.tblObjectStateByRefidToolState otst
join tops.tblObjectStateByRefidUploadState oust
join to.tblSapr3Data sapr3data
where
ts.idSession=:idSession
order by
to.objectName ASC, tot.objectTypeCode ASC
]]>
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 (HQL) generated the following SQL for which I inserted the parameters:
select
sum(activity0_.calculated_work) as col_0_0_
, employee2_.id as col_1_0_
, projectele1_.id as col_2_0_
from
activity activity0_
inner join generic_object activity0_1_ on activity0_.id=activity0_1_.id
left outer join project_element projectele1_ on activity0_.project_element_id=projectele1_.id
left outer join employee employee2_ on activity0_.owner_id=employee2_.id
left outer join org_unit orgunit3_ on employee2_.org_unit_id=orgunit3_.id
where
activity0_1_.deleted=0 and
activity0_.client_id=22
group by
employee2_.id order by SUM(activity0_.calculated_work) DESC
Error message: Column 'project_element.id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I executed this SQL directly in the SQL Server Studio with the same result. I commented this line:
, projectele1_.id as col_2_0_
The SQL was then accepted by the SQL Server
The table project_element definitely has a column with the name id it is also referenced in the LEFT OUTER JOIN and there this column is not causing an error.
Removing the alias projectele1_ had no effect.
To me this looks like a really simple SQL statement. I cannot imagine what is wrong with it and the error message is not helping at all. Any ideas what could be wrong with the SQL?
Your SQL syntax is wrong.If you add projectele1_.id to group by clause it will work.Only aggregate functions work in select statement with group by clause.Or if you remove projectele1_.id from select it will work fine.
My mistake. I should have read the error message several times. projectele1_id is not in the group by clause. MS SQL does not allow to include such a column into the select list. This seems to be a consistency check.
Too bad though that the usage of HQL leads to such an exception in SQL Server but not in MySQL Server.
How to add groupBy criteria to the code below? Because if I add criteriaQuery.groupBy(from.get(minutis.Preke_.prId)); - I get exactly the same SQL statement (without groupBy):
CriteriaBuilder cb = MinutisManager.getInstance().getCriteriaBuilder();
CriteriaQuery criteriaQuery = cb.createQuery(minutis.Preke.class);
Root<minutis.Preke> from = criteriaQuery.from(minutis.Preke.class);
from.fetch(minutis.Preke_.tiekejai, JoinType.LEFT).fetch(minutis.PrekeTiekejas_.tiekejas, JoinType.LEFT);
//criteriaQuery.groupBy(from.get(minutis.Preke_.prId));
TypedQuery<minutis.Preke> typedQuery = MinutisManager.getInstance().createQuery(criteriaQuery);
typedQuery.setFirstResult(0);
typedQuery.setMaxResults(100);
typedQuery.getResultList();
EDIT 1:
criteriaQuery.distinct(true) is not an option for me. Because that command hangs the whole statement and if I use EXPLAIN:
If I use GROUP BY on the query, then EXPLAIN is:
EDIT 2:
I get this SQL statement with and without criteriaQuery.groupBy(from.get(minutis.Preke_.prId));
SELECT ... FROM preke t1 LEFT OUTER JOIN preke_tiekejas t0 ON (t0.pr_id = t1.pr_id) LEFT OUTER JOIN tiekejas t2 ON (t2.tiek_id = t0.tiek_id) LEFT OUTER JOIN gamintojas t3 ON (t3.gam_id = t1.gam_id) LEFT OUTER JOIN google_compare t4 ON (t4.pr_id = t1.pr_id) LEFT OUTER JOIN grupe t5 ON (t5.pgs_id = t1.pgs_id) LEFT OUTER JOIN preke_kaina t6 ON (t6.pr_id = t1.pr_id) ORDER BY t1.pr_id LIMIT ?, ?
The SQL for the GROUP BY query should definitely contain a GROUP BY. Ensure that you are compiling and deploying the code correctly.
It could be a bug that the group by is ignored, as normal group by queries will not select object, but aggregated values. Check that you are using the latest release, and perhaps log a bug, or try JPQL.
In general your query does not make any sense, normally on a group by query you can only select the fields that you grouped by, or aggregation functions.
Perhaps consider batch fetching instead of join fetching.
http://java-persistence-performance.blogspot.com/2010/08/batch-fetching-optimizing-object-graph.html
I will file a bug in Eclipselink, because if I change fetch line with QueryHints, everything works:
Change this (with this line I get duplicate Preke entities with populated children entities):
from.fetch(minutis.Preke_.tiekejai, JoinType.LEFT).fetch(minutis.PrekeTiekejas_.tiekejas, JoinType.LEFT);
To this (with this lines I get unique Preke entities with populated children entities):
typedQuery.setHint(QueryHints.LEFT_FETCH, "Preke.tiekejai");
typedQuery.setHint(QueryHints.LEFT_FETCH, "Preke.tiekejai.tiekejas");
I get my desired result.
EDIT 1:
The bug really exists, now max resulsts is not working. Both cases typedQuery is identical.
typedQuery.setMaxResults(100);
System.out.println(typedQuery.getResultList().size()); //prints 73
typedQuery.setMaxResults(500);
System.out.println(typedQuery.getResultList().size()); //prints 413
No problem, I found the bug report, here it is, just in case someone else needs it.Criteria api ignores group by statement
I'm trying to write a HQL/Criteria/Native SQL query that will return all Employees that are assigned to a list of Projects. They must be assigned to all Projects in order to be selected.
An acceptable way of achieving this with native SQL can be found in the answer to this question: T-SQL - How to write query to get records that match ALL records in a many to many join:
SELECT e.id
FROM employee e
INNER JOIN proj_assignment a
ON e.id = a.emp_id and a.proj_id IN ([list of project ids])
GROUP BY e.id
HAVING COUNT(*) = [size of list of project ids]
However, I want to select all fields of Employee (e.*). It's not possible to define SQL grouping by all the columns(GROUP BY e.*), DISTINCT should be used instead. Is there a way to use DISTINCT altogether with COUNT(*) to achieve what I want?
I've also tried using HQL to perform this query. The Employee and ProjectAssignment classes don't have an association, so it's not possible to use Criteria to join them. I use a cross join because it's the way to perform a Join without association in HQL. So, my HQL looks like
select emp from Employee emp, ProjectAssignment pa
where emp.id = pa.empId and pa.paId IN :list
group by emp having count(*) = :listSize
However, due to a bug in Hibernate, GROUP BY entity does not work. The SQL it outputs is something like group by (emptable.id).
Subquerying the assignment table for each project (dynamically adding and exists (select 1 from proj_assignment pa where pa.emp_id=e.id and pa.proj_id = [anId]) for each project in the list) is not an acceptable option.
Is there a way to write this query properly, preferrably in HQL (in the end I want a List<Employee>), without modifying mappings and without explicitly selecting all columns in the native SQL ?
EDIT: I'm using Oracle 10g and hibernate-annotations-3.3.1.GA
How about:
select * from employee x where x.id in(
SELECT e.id
FROM employee e
INNER JOIN proj_assignment a
ON e.id = a.emp_id and a.proj_id IN ([list of project ids])
GROUP BY e.id
HAVING COUNT(*) = [size of list of project ids]
)
I've found an alternative way to achieve this in HQL, it's far more inefficient than what I'd like, (and than what is really possible without that nasty bug) but at least it works. It's better than repeating subselects for each project like
and exists (select 1 from project_assignment pa where pa.id = someId and pa.emp_id = e.id)
It consists of performing a self-join subquery in order to find out, for each of the Employees, how many of the projects in the list they are assigned to, and restrict results to only those that are in all of them.
select e
from Employee
where :listSize =
(select distinct count(*)
from Employee e2, ProjectAssignment pa
where
e2.id = pa.id_emp and
e.id = e2.id
and pa.proj_id IN :projectIdList
)