one 2 many jpa qry with join - java

I am trying to use jpa with join to qry one to many entities
Entity Table Unit (one)
Entity Table Appartment (many)
I am using the following JPA
#Query("Select u from Unit u inner join u.appartmentList a " +
"where u.unitNumber IN :unitNumbers " +
"and a.appNumber= :appNumber")
Page findApt(#Param("unitNumbers") Collection<String> unitNumbers,
#Param("appNumber") Integer appNumber,
Pageable pageable);enter code here
I need to be able to get 2 appartments (one in each unit passed as unita,unitb).
if I do a GET for ../findStuff?unitNumbers=unita,unitb&appNumber=1
But I get all appartments in each unit instead, not just appNumber=1 in each unit.
Any idea on how to achieve this would be greatly appreciated
Thank you

You need to query on Appartment.
#Query("select a from Appartment a where" +
" a.appNumber= :appNumber and a.unit.unitNumber IN :unitNumbers"
If unit is lazy fetched, you may want to fetch it with the first query, so the query becomes:
#Query("select a from Appartment a join fetch a.unit where" +
" a.appNumber= :appNumber and a.unit.unitNumber IN :unitNumbers"

Related

Spring Boot JPA LEFT JOIN in 3 tables

I'm using Spring Boot, and trying to utilize HQL to set up a LEFT JOIN between 3 tables.
The three entites I have are Usage, SubscriptionPeriod and Subscription. Necessary Hibernate annotation have been set in the entity classes.
Usage and SubscriptionPeriod : Many to One (a SubscriptionPeriod can have multiple Usage)
Subscription and SubscriptionPeriod : Many to One (a Subscription can have multiple SubscriptionPeriod).
Goal : I want to fetch all the usages by providing a subscription id and usage has title 'NEW'. And, I want to do it in a single database request
I have:
String hql =
"SELECT DISTINCT u " +
"FROM Usage u " +
"LEFT JOIN u.subscriptionPeriod p " +
"LEFT JOIN p.subscription s " +
"WHERE s.remoteId = :remoteId AND u.title='NEW'";
Currently, there seems to be a syntax error around "FROM Usage ". It reads " can not resolve symbol Usage"
How can I achieve what I want? I am open to listen to alternative solutions as well. Thanks.
I was probably thinking it in a probably more convoluted way. This #Query on a method works great. Hope this will be useful for somebody.
#Query(
"SELECT u " +
"FROM usages u " +
"LEFT JOIN u.subscriptionPeriod p " +
"LEFT JOIN p.subscription s " +
"WHERE u.paymentStatus = 'NEW' AND s.remoteId = :remoteId"
)
public List<Usage> find(#Param("remoteId") String param)

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

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.

Spring data jpa + joining 2 tables

I have 2 entity classes Product and ProductAltID with no #OnetoMany mapping defined between them.
I want to do something like this
select p from ProductAltid inner join Product pai
where p.id = pai.id
How can I achieve this?
Add this method to the ProductAltId repository (choosing that one because the query returns ProductAltIds):
#Query("select pai from ProductAltId as pai "
+ "where pai.id in (select p.id from Product as p)")
List<ProductAltId> findForAllProducts();
I switched the aliases around, they seem backward in your example.

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.

Categories

Resources