Hibernate Query Returning Duplicate results - java

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

Related

join and where clause in hibernate

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

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.

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.

hql select table records from many to one relationship tables

I've these three tables.
UserTrackRecord -> id, profile_id(fk), object_profile_id(int)
Profile and -> id
ProfilePersonalInfo-> id, profile_id(fk), firstname, lastname
The profile_id and object_profile_id are for the purpose that when somebody sends me a request of friendship, the object_profile_id is my profile id and the foreign key is the profile id of the sender.
one profile has many usertrackrecords.
one profile has one profilepersonalinfo (There are two more tables just like profilepersonalinfo which are basicinfo and backgroundinfo having profileid as fk).
I've got my own profile id(objecct_profile_id) say 1. Now, I wanna get the firstname, lastname of the request sender and information from the other two tables as well.
The sql query which i made is
select utr.profile_profile_id, ppi.dob, ppi.first_name, ppi.last_name, "
+ "pbi.religion, pbi.city_birth, pbi.country_birth from "
+ "user_track_record utr "
+ "inner join profile_personnel_info ppi on ppi.profile_profile_id=utr.profile_profile_id "
+ "inner join profile_background_info pbi on pbi.profile_profile_id=utr.profile_profile_id "
+ "where utr.object_profile_id=1
which is working fine.
In hql, when i simplified my query at most, it became
Select * from UserTrackRecord utr inner join ProfilePersonalInfo ppi
but id didn't work and it gave me the outer or full join must be followed by path expression query exception.
I posted the same question before, but somebody de-voted it :( so i did some more R&D but didn't find a solution.
I understand why this was voted down previously. Please go thru the hibernate documentation before posting the question.
As mentioned above hibernate works with entities, you need to mention an alias when you are joining tables in hibernate.
Select utr from UserTrackRecord utr inner join utr.profilePersonalInfo ppi and so on......
Since you have not provided your entities, I am assuming that UserTrackRecord is having an attribute called profilePersonalInfo which is of Type ProfilePersonalInfo. If not then please go thru Hibernate associations.

HQL ERROR: Path expected for join

I keep trying variations of this query and can't seem to make this happen. I've also referenced this post: Path Expected for Join! Nhibernate Error and can't seem to apply the same logic to my query. My User object has a UserGroup collection.
I understand that the query needs to reference entities within the object, but from what I'm seeing I am...
#NamedQuery(
name = "User.findByGroupId",
query =
"SELECT u FROM UserGroup ug " +
"INNER JOIN User u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)
select u from UserGroup ug inner join ug.user u
where ug.group_id = :groupId
order by u.lastname
As a named query:
#NamedQuery(
name = "User.findByGroupId",
query =
"SELECT u FROM UserGroup ug " +
"INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)
Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.
You need to name the entity that holds the association to User. For example,
... INNER JOIN ug.user u ...
That's the "path" the error message is complaining about -- path from UserGroup to User entity.
Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.
You'll be better off using where clauses. Hibernate does not accept inner joins for tables where the PK/FK relationship is not there between Entities
do
SELECT s.first_name, s.surname, sd.telephone_number FROM Student s, StudentDetails sd WHERE s.id = sd.student_id
instead of
SELECT s.first_name, s.surname, sd.telephone_number FROM Student s INNER JOIN StudentDetails sd on s.id = sd.student_id
The latter will only work if Student's id (s.id) is referenced as FK on StudentDetails (sd.student_id)) table design / erd

Categories

Resources