join and where clause in hibernate - java

I am using join and where clause in hibernate 3.but i cant reach the solution.I got the error.
Query qry= session.createQuery("SELECT addemployee.eid,addemployee.fname,addemployee.location,"
+ "empdet.jtitle,empdet.leadname FROM addemployee LEFT JOIN empdet ON addemployee.eid = empdet.eid WHERE (addemployee.eid ='"+id+"')");
List l = qry.list();
Iterator it=l.iterator();
while(it.hasNext())
{
Object rows[] = (Object[])it.next();
System.out.println(rows[0]+separator+rows[1]+separator+rows[2]+separator+rows[3]+separator+rows[4]);
}
Issue: org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ON near line 1, column 127 [SELECT addemployee.eid,addemployee.fname,addemployee.location,empdet.jtitle,empdet.leadname FROM addemployee LEFT JOIN empdet ON addemployee.eid = empdet.eid WHERE (addemployee.eid ='206')]

Try to use session.createSQLQuery() instead.
and don't put enclosed apostrophe (''), you are inputting numbers, not varchar.
like this.
Query qry= session.createSQLQuery("SELECT addemployee.eid,addemployee.fname,addemployee.location,"
+ "empdet.jtitle,empdet.leadname FROM addemployee LEFT JOIN empdet ON addemployee.eid = empdet.eid WHERE (addemployee.eid ="+id+")");

Hibernate Session's createQuery() method requires valid HQL syntax. You can check how to write joins here.
Basically, in HQL you work with your entities, not SQL tables. So you don't need to write ON, because you already map association between entities.
If you still want to write native SQL query, you need to use
session.createSQLQuery(); instead

Related

Hibernate Query Returning Duplicate results

I am trying to join 3 tables to get an output. Following are the tables
player_match(match_id,team_id,player_id)
player(player_id,name,......)
team(team_id,name......)
All the tables have equivalent classes assigned.
Following is the SQL query that I am running and getting the correct results.
select * from player_match M
inner join team T
on M.team_id = T.team_id
inner join player P
on P.player_id = M.player_id
where M.match_id = 335987;
I am running the following Named query in PlayerMatch java class. PlayerMatch class has Match and Team objects in it. Both of these objects are mapped #ManyToOne.
#NamedQuery(name="getMatchData",query="select PM from PlayerMatch PM "
+ "inner join Team T on PM.teamId = T.teamId "
+ "inner join Player P on PM.playerId = P.playerId "
+ "where PM.matchId = :matchID")
When I run the above hibernate query I get 22 results which is correct, but the contents of all the results are the same.
The SQL query that I have mentioned above returns 22 non duplicate rows.
I think I am messing up somewhere in the Hibernate query but can't figure out where.
Your HQL query is structured similarly to an SQL query. You shouldn't need to specify the 'on' conditions as they are derived from the hibernate schema.
See hibernate documentation for more info on hql joins:
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-joins

SQL Query builder utility

I have a Set of columns and Tables, in respective drop downs, I am working on a Code to generate a dynamic SQL based on the Table-Column selection
It's working in case of simple Select statements but in the case of Multiple Joins, I am trying to figure out a Syntax for handlin Right and Left Joins.
Please help..this is the Error for SQL Syntax
1)
(Select dbo.Employee.Dept_ID,dbo.Employee.Emp_ID,dbo.Employee.Emp_Name,dbo.Employee_DataVal.DeptNo,
dbo.Employee_DataVal.EmpName,dbo.Employee_DataVal.EmpNo,dbo.Employee_DataVal.Salary,dbo.Emp_Sal.Emp_ID,dbo.Emp_Sal.Salary
FROM Employee
INNER JOIN Employee_DataVal
ON Employee.Dept_ID = Employee_DataVal.DeptNo
OR Employee_DataVal.EmpName = Employee.Emp_Name)
LEFT JOIN Emp_Sal
ON Employee.Emp_ID = Emp_Sal.Emp_ID
Incorrect syntax near the keyword 'LEFT'.
2)Select dbo.Employee.Dept_ID,dbo.Employee.Emp_ID,
dbo.Employee.Emp_Name,dbo.Employee_DataVal.DeptNo,
dbo.Employee_DataVal.EmpName,dbo.Employee_DataVal.EmpNo
,dbo.Emp_Sal.Emp_ID,dbo.Emp_Sal.Salary
FROM Employee INNER JOIN Employee_DataVal
ON Employee.Emp_ID = Employee_DataVal.EmpNo
AND Employee.Dept_ID = Employee_DataVal.DeptNo
LEFT JOIN Employee
ON Employee_DataVal.EmpName = Employee.Emp_Name
The objects "Employee" and "Employee" in the FROM clause have the same exposed names. Use correlation names to distinguish them.
PS: Running this sql on SQL server
This is a common problem when working with complex dynamic SQL strings on a string basis - the correct handling of the SQL syntax in its string form is difficult, and it is easy to create SQL injection vulnerabilities as well.
SQL builder APIs like jOOQ and others are very well suited for this task. I'm not sure what exactly the problem was in your case, but let's just assume that the last LEFT JOIN is optional in your query. You could write a query like this:
List<Field<?>> c = new ArrayList<>(Arrays.asList(
EMPLOYEE.DEPT_ID,
EMPLOYEE.EMP_ID,
EMPLOYEE.EMP_NAME,
EMPLOYEE_DATAVAL.DEPTNO,
EMPLOYEE_DATAVAL.EMPNAME,
EMPLOYEE_DATAVAL.EMPNO,
EMPLOYEE_DATAVAL.SALARY
));
Table<?> t = EMPLOYEE
.join(EMPLOYEE_DATAVAL)
.on(EMPLOYEE.DEPT_ID.eq(EMPLOYEE_DATAVAL.DEPTNO)
.or(EMPLOYEE_DATAVAL.EMPNAME.eq(EMPLOYEE.EMP_NAME));
if (someCondition) {
t = t.leftJoin(EMP_SAL).on(EMPLOYEE.EMP_ID.eq(EMP_SAL.EMP_ID));
c.addAll(Arrays.asList(
EMP_SAL.EMP_ID,
EMP_SAL.SALARY
));
}
Result<?> result =
ctx.select(c)
.from(t)
.fetch();
Speaking directly to the syntax errors:
The parentheses in this statement are invalid. Removing them will solve the problem.
The table Employee is used twice in the FROM clause. You must alias the tables for this to work.
Select dbo.Employee.Dept_ID,dbo.Employee.Emp_ID,
dbo.Employee.Emp_Name,dbo.Employee_DataVal.DeptNo,
dbo.Employee_DataVal.EmpName,dbo.Employee_DataVal.EmpNo
,dbo.Emp_Sal.Emp_ID,dbo.Emp_Sal.Salary
FROM Employee e1 INNER JOIN Employee_DataVal
ON e1.Emp_ID = Employee_DataVal.EmpNo
AND e1.Dept_ID = Employee_DataVal.DeptNo
LEFT JOIN Employee e2
ON Employee_DataVal.EmpName = e2.Emp_Name
Speaking to your broader question, the concept of a generic SQL query generator is quite common and has had several implementation. You won't find full implementation guidance in a forum such as this.
Cheers!
You are using LEFT Join same as the Self join. which is actually creating the problem.
In first case error is coming because of the wrong ) in wrong place as pointed below; Which making the end of query and so LEFT JOIN throwing an error. the ) must be at end of the query.
FROM Employee
INNER JOIN Employee_DataVal
ON Employee.Dept_ID = Employee_DataVal.DeptNo
OR Employee_DataVal.EmpName = Employee.Emp_Name ) <--Here
LEFT JOIN Emp_Sal
In second case, you are trying to do a self join to the same table in that case as the error already suggested you, you need to use correlation names like
FROM Employee emp1 <-- Here used a table alias emp1
INNER JOIN Employee_DataVal ed
ON emp1.Emp_ID = ed.EmpNo
AND emp.Dept_ID = ed.DeptNo
LEFT JOIN Employee emp2 <-- Here used a different table alias emp2
ON ed.EmpName = emp2.Emp_Name
Moreover, the LEFT JOIN Employee won't make any sense here and which can simply be modified to below code
FROM Employee emp1
INNER JOIN Employee_DataVal ed
ON emp1.Emp_ID = ed.EmpNo
AND emp.Dept_ID = ed.DeptNo
AND emp.Emp_Name = ed.EmpName <-- here by adding another join condition

Hibernate generates error SQL like ".=."

I have 3 tables in Oracle DB which relationship is #ManyToMany. So I have 2 significant tables and one for mappings.
I create a classes with name (if you want I can show my classes) named Entities, Keywords (I understand that naming is not correct but this is not my project I only do optimizations).
I use hibernate version 4.3.4.
I write query like this:
session = HibernateUtil.getSessionFactory().openSession();
String sql = "SELECT DISTINCT r FROM Rules r, Entities e " +
" WHERE r.entities = e.rules " +
" AND e IN :entities ";
Query query = session.createQuery(sql);
query.setParameterList("entities", entitiesList);
List<Rules> rulesList = query.list();
BUT! Hibernate generate strange SQL
Hibernate:
select
rules0_.rule_id as rule_id1_11_,
rules0_.rule as rule2_11_
from
rules rules0_,
entities entities1_,
rules_entities entities2_,
entities entities3_,
rules_entities rules4_,
rules rules5_
where
rules0_.rule_id=entities2_.rule_id
and entities2_.entity_id=entities3_.entity_id
and entities1_.entity_id=rules4_.entity_id
and rules4_.rule_id=rules5_.rule_id
and .=.
and (
entities1_.entity_id in (
? , ? , ? , ?
)
)
When I try to execute this query I receive that error:
java.sql.SQLException: ORA-00936: missing expression
When I copy this query to OracleDevepoler he didn`t like this expression "and .=.". Without that query executes correct.
What am I doing wrong ?
Maybe you used bad join in your query? From context i conclude that you should use something like that:
"SELECT DISTINCT r FROM Rules r inner join r.entities e " +
" WHERE e IN :entities ";
I think the correct query could be
select distinct e.rules from Entities where e.entityId in :entities
This is if Keywords is your join table and you have a collection of rules in Entities
If it isn't, can you show the mappings please, it could help.

Creating inner query in hibernate

how to add a set parameter() metheod inside the inner query in hibernate?
I have try to do like this but already have a errors
this is my code
Query query=session.createQuery("select eq.euipmentName,eq.type from Euipment eq where eq.id in(select euipment from Quotation qt where qt. supQuotation=:ids)");
query.setParameter("ids",id);
list = (List<Euipment>)query.list();
I've done some corrections about your query:
1. qt. supQuotation has a space, I've removed
2. euipment in you sub query haven't alias, I add qt
String hql =
"select eq.euipmentName,eq.type " +
" from Euipment eq " +
" where eq.id in (select qt.euipment from Quotation qt where qt.supQuotation = :ids)";
Query query = session.createQuery(hql);
query.setParameter("ids",id);
list = (List<Euipment>)query.list();
Tell me, if it's OK
If not OK, please post here the error, and check if you have put in hibernate mappping file your classes
From Hibernate Documentation:
Execution of native SQL queries is controlled via the SQLQuery
interface, which is obtained by calling Session.createSQLQuery().
createQuery() creates Query object using the HQL syntax.
createSQLQuery() creates Query object using the native SQL syntax.
So replace createQuery with createSQLQuery for native SQL query.
Try with Criteria
Criteria c = getSession().createCriteria(Euipment.class, "e");
c.createAlias("e.quotation", "q"); // inner join by default
c.add(Restrictions.eq("q.supQuotation", id));
list = (List<Euipment>)c.list();

QuerySyntaxException : Hibernate not recognizing the postgres query syntax in java

I am facing problem of executing the following query in java using hibernate for postgres tables.
The query is made up to retrive the data from 3 tables using Inner Joins.
Query :
QryJourney = "SELECT journey.id , journey.operatingday, journey.linename, journey.scheduledeparture, journey.scheduledeparturestopname, journeydetail.stopname , journeydetail.latitude, journeydetail.longitude FROM journey left join journey_journeydetail ON journey.id = journey_journeydetail.journey_id left JOIN journeydetail ON journey_journeydetail.journeydetails_id = journeydetail.id WHERE journey.id = '155815228' ORDER BY journeydetail.schedulearrival";
as soon as it executes, following exception occured.
Exception :
Exception in thread "main" org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ON near line 1, column 268 [SELECT journey.id , journey.operatingday, journey.linename, journey.scheduledeparture, journey.scheduledeparturestopname, journeydetail.stopname , journeydetail.latitude, journeydetail.longitude FROM de.db.journeyTracker.model.journey left join journey_journeydetail ON journey.id = journey_journeydetail.journey_id left JOIN journeydetail ON journey_journeydetail.journeydetails_id = journeydetail.id WHERE journey.id = '155815228' ORDER BY journeydetail.schedulearrival]
Tis query works 100% fine at postgres while executing on its SQL Pane.
Anybody having any idea?
Regards
Usman
Hibernate queries are written in Hibernate Query Language (HQL) not in native SQL. Rephrase your query in HQL or use a native query to use SQL with Hibernate.
Hibernate is an object-relational mapper. It won't just give you a result set. If you want that, use JDBC directly, using PgJDBC.
If you want native domain objects as query results, use Hibernate with HQL or via a native query mapping. Native queries are fiddlier becuse you have to explicitly tell Hibernate how all the result columns map to your result objects.

Categories

Resources