I have a following entity structure.
Venue -- n:1 -- Schedule -- 1:n -- Event
I have a query to get counts of all schedule in Venues:
SELECT v, count(s.event) FROM Venue v
LEFT JOIN i.schedule s
GROUP BY i.id ORDER BY count(s.event) asc;
The problem is that this query will never output venues, that have zero events. The problem is with Hibernate, which generates following:
select ..., count(schedule4_.event_id) as col_7_0_
from Venue venue0_
left outer join event_schedule schedule4_ on venue0_.id=schedule4_.venue_id,
Event event5_
where schedule4_.event_id=event5_.id and ...
You can see, that Hibernate tries to join Event on Schedule even though I did not request that. Obviously if the Schedule does not exist, joining Event does not make any sense.
(I simpified the query, if there is some typo, it should not have any impact on the problem).
Try with the following query:
select v.id, count(e.id) from Venue v
left join v.schedule s
left join s.events e
group by v.id order by count(e.id) asc;
Related
I have 4 tables:
job
client
order
client
client
state
state
name
I need to get a client's state name from a job OR order. If job is not null get from job, else get from order.
I tried something like this:
LEFT JOIN job.client jc
LEFT JOIN order.client oc
LEFT JOIN COALESCE(jc.state, oc.state) clientState
but I get an unexpected token: COALESCE exception.
I also tried:
LEFT JOIN job.client jc
LEFT JOIN order.client oc
LEFT JOIN CASE WHEN job IS NOT NULL THEN jc.state ELSE oc.state END clientState
but I get an unexpected token: CASE exception.
Any idea on how to solve this? Should I try multiple JOINS with state table (jc.state and oc.state) and use the CASE in the projection? Isn't there an easier way?
Thanks in advance
Extra info:
This query could be solved like the example below. My main question is if there is a better way of doing this:
SELECT CASE WHEN jcClientState IS NOT NULL THEN jcClientState.code ELSE ocClientState.code END
FROM job job
LEFT JOIN anotherTable anotherTable
LEFT JOIN job.client jc
LEFT JOIN anotherTable.order oc
LEFT JOIN jc.state jcClientState
LEFT JOIN oc.state ocClientState
Assuming HQL supports coalesce (appears as such when doing a quick search), then you can use coalesce like this:
select coalesce(table1.state, table2.state, 'unknown') as state
from table1
left join table 2
on table2.id = table1.id
The coalesce will grab the first non-null value.
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
]]>
I have been trying to get Hibernate to generate me a query with a subquery in its where clause. I've used this answer as a base to help me going, but this question mentioned only one table.
However, this is what I would need (in SQL):
SELECT [...]
FROM a
LEFT OUTER JOIN b on a.idb = b.idb
LEFT OUTER JOIN c on b.idc = c.idc
[...]
LEFT OUTER JOIN k out on j.idk = k.idk
WHERE k.date = (SELECT max(date) from k in where in.idk = out.idk) OR k.date is null
As I am not very used to using Hibernate, I'm having trouble specifying these inner joins while navigating in the inner constraints.
I was able to re-create the initial criteria as in the linked answer, but I can't seem to join the criteria and the rootCriteria.
If the entities are properly joined with #ManyToOne annotations, simply joining the criteria to the previous table will be enough to propagate the criteria to the whole query.
The following code seems to work properly to add the WHERE clause I'm looking for.
DetachedCriteria kSubquery = DetachedCriteria.forClass(TableJPE.class,"j2");
kSubQuery = kSubQuery.createAlias("k","k2");
kSubQuery.setProjection(Projections.max("k2.date"));
kSubQuery = kSubQuery.add(Restrictions.eqProperty("j.id", "j2.id"));
rootCriteria.add(Restrictions.disjunction()
.add(Subqueries.propertyEq("k.date",kSubQuery))
.add(Restrictions.isNull("k.date")));
I have 2 entites , each stored in mysql table.
1. productA : {productId(pk) , desc , date}
2. productB : {productId(pk) , quantity,type,date}
I want to run this SQL query:
select a.*
from productA a left join productB b using(productId)
where b.productId is null
(return all the products from a that not exists in b)
Is it possible to write this query in Hibernate?
Thank you!!
Is it possible to write this query in Hibernate?
Yes, of course. From JPA specification 2.1 (4.4.5.2 Left Outer Joins):
LEFT JOIN and LEFT OUTER JOIN are synonymous. They enable the
retrieval of a set of entities where matching values in the join
condition may be absent. The syntax for a left outer join is
LEFT [OUTER] JOIN join_association_path_expression [AS] identification_variable
[join_condition]
An outer join without a specified join condition has an implicit join
condition over the foreign key relationship corresponding to the
join_association_path_expression. It would typically be mapped to a
SQL outer join with an ON condition on the foreign key relationship as
in the queries below: Java Persistence query language:
SELECT s.name, COUNT(p)
FROM Suppliers s LEFT JOIN s.products p
GROUP BY s.name
SQL:
SELECT s.name, COUNT(p.id)
FROM Suppliers s LEFT JOIN Products p
ON s.id = p.supplierId
GROUP By s.name
An outer join with an explicit ON condition would cause an additional
specified join condition to be added to the generated SQL: Java
Persistence query language:
SELECT s.name, COUNT(p)
FROM Suppliers s LEFT JOIN s.products p
ON p.status = 'inStock'
GROUP BY s.name
SQL:
SELECT s.name, COUNT(p.id)
FROM Suppliers s LEFT JOIN Products p
ON s.id = p.supplierId AND p.status = 'inStock'
GROUP BY s.name
Note that the result of this query will be different from that of the
following query:
SELECT s.name, COUNT(p)
FROM Suppliers s LEFT JOIN s.products p
WHERE p.status = 'inStock'
GROUP BY s.name
The result of the latter query will exclude suppliers who have no
products in stock whereas the former query will include them.
An important use case for LEFT JOIN is in enabling the prefetching of
related data items as a side effect of a query. This is accomplished
by specifying the LEFT JOIN as a FETCH JOIN as described below.
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
)