how to use left outer join in hibernate using hibernate query language - java

hi i am trying to execute the hql query using left outer join it is thowing exception as org.hibernate.hql.ast.QuerySyntaxException: unexpected token: on near line 1, can pls tell me what is worng in this query
select * from CreditCardDetails cred left outer join CustomerHistory custHist on cred.creditCardDetailsId=custHist.creditCardDetailsId and custHist.cardA=0000

Assuming that you have an association named history that relates the entity CreditCardDetails to CustomerHistory.
from CreditCardDetails cred
left outer join cred.history custHist
with custHist.cardA=0000

Related

HQL - COALESCE or CASE on LEFT JOIN

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.

#Query for joining two tables

I am trying to join two entities in a third one using #Query method.
#Query("SELECT new com.concretepage.entity.DeptEmpDto(d.departmentId,d.departmentName,d.managerId,d.locationId,e.employeeId,e.firstName,e.lastName,e.phoneNumber,e.hireDate,e.jobId,e.salary,e.commissionPct) FROM Employee e INNER JOIN Department d")
List <DeptEmpDto> fetchEmpDeptDataInnerJoin();
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1.
I cannot understand where is my mistake.Any help will be appreciated :).
You missed the joining condition after joining tables using ON clause. So just change your query with this:
#Query("SELECT new com.concretepage.entity.DeptEmpDto(d.departmentId,d.departmentName,d.managerId,d.locationId,e.employeeId,e.firstName,e.lastName,e.phoneNumber,e.hireDate,e.jobId,e.salary,e.commissionPct) FROM Employee e INNER JOIN Department d on e.joining_column_from_table1=d.joining_column_from_table2")
Make sure to replace joining_column_from_table1 and
joining_column_from_table2 with your column names from table
Employee and Department respectively

Hibernate query with subquery in WHERE clause and multiple joins

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")));

Left Join in HQL - Hibernate query

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.

Execute left join query in JPA

I have two tables, one for party and one for scorecard template mapping. The scorecard template mapping table has a foreign key back to the party (on id). I want to find a list of all of the parties that have scorecard template mapping details.
But I get an error which says :
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token:
on near line 1, column 172 [select new
ScorecardTemplateMapping(p,temMap.scoTemplate,temMap.wrkFlwTemplate)
from com.kpisoft.common.web.domain.Party p left outer join
ScorecardTemplateMapping temMap on temMap.organization.id=p.id and
temMap.gradeType.id=:gradeType where
p.organization.organizationTypeId=:orgType and p.clientId=:clientId
order by p.organization.name]
This is my query:
Query q = entityManager.createQuery("select new
ScorecardTemplateMapping(p,temMap.scoTemplate,temMap.wrkFlwTemplate)
from Party p left outer join ScorecardTemplateMapping temMap on
temMap.organization.id=p.id and temMap.gradeType.id=:gradeType where
p.organization.organizationTypeId=:orgType and p.clientId=:clientId
order by p.organization.name");
I have no idea why this isn't working. Please help!
Error message about syntax error is quite clear:
unexpected token: on
There is no support to make join with ON [conditional] in JPQL (ON is not reserved word). How joins are made in JPQL, is told for example here. It boils down to that you have to present join condition in where clause.

Categories