#Query for joining two tables - java

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

Related

SQL generated by Hibernate invalid for MS SQL

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.

JPA: Left join not working with "is null" in where clause

I am using EclipseLink (2.4, 2.5 and 2.6) on a very simple project where I have a Department entity and each Department links to an Employee entity which is the manager of the Department.
I am currently unable to make this simple query work:
select d from Department d where d.manager is null
Returns 1 row
select d from Department d left join fetch d.manager where d.manager is null
Returns 0 row
I am using Eclipselink over an H2 database. The SQL query generated does not seem to create a left join but rather an inner join which obviously will fail.
SELECT t1.ID, t1.MANAGER_ID, t0.ID, t0.NAME FROM EMPLOYEE t0, DEPARTMENT t1
WHERE ((t1.MANAGER_ID IS NULL) AND (t0.ID = t1.MANAGER_ID))
Is this a bug or is it something wanted? Or could someone help me fixing this?
Happy to provide the code and example if anyone wants it, or more information.
It seems unsafe to reference an entity that was returned in a query as a side effect by using a FETCH JOIN. The JPA specification tries to prohibit such queries at least for multi-valued associations (JSR 338, section 4.4.5.3):
It is not permitted to specify an identification variable for the objects referenced by the right side of the FETCH JOIN clause, and hence references to the implicitly fetched entities or elements cannot appear elsewhere in the query.
Your query executed on EclipseLink and Hibernate yields different results (EclipseLink 2.6.3: no results, Hibernate 4.3.11: all departments with no manager):
select d from Department d left join fetch d.manager where d.manager is null
To solve your problem a subquery could be used. A portable JPQL query could look like this (same results in EclipseLink and Hibernate):
select d1 from Department d1 left join fetch d1.manager where exists
(select d2 from Department d2 where d2.manager is null and d1 = d2)

How do I set a Restriction in Hibernate to target a column in either one of two joined tables?

I'm joining one table to another. The join works. I want to restrict the results to records with an "Error" message that can be in either table. When I do the following, I get no results back, yet I know there should be 2.
Criteria criteria = session.createCriteria(TableName.class);
criteria.createAlias("someList", "things");
Criterion restriction1 = Restrictions.eq("status", "Error");
Criterion restriction2 = Restrictions.eq("things.anotherStatus", "Error");
criteria.add(Restrictions.or(restriction1, restriction2));
finalList = criteria.list();
I noticed that the restrictions by themselves actually work. So, if I only do the first restriction on the original table with no alias OR if I only do the second restriction on the alias table, then I get 1 result each time.
Also, a simple join SQL query like the one below works as expected:
Select count(*)
From table1 t1
Left join table2 t2 on t1.id = t2.another_id
Where t1.status = 'ERROR' or t2.anotherStatus = 'ERROR'
How can I get this right in Hibernate?
EDIT 1: I now see that Hibernate does an Inner Join when I use the #JoinColumn annotation. How can I change it to do an Outer Join instead?
EDIT 2: Even adding #Fetch(FetchMode.JOIN) still results in an inner join! What gives? The documentation clearly says it will do an outer join. The annotation now looks like this:
#OneToMany
#JoinColumn(name="ID_FK")
#Fetch(FetchMode.JOIN)
private List<Thing> things;
Answer: use criteria.createAlias("someList", "things", JoinType.LEFT_OUTER_JOIN); instead.
Explanation: When no JoinType is specified, createAlias does an inner join by default.

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.

HQL/SQL/Criteria to join-match all records in a given list while selecting all fields

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
)

Categories