Spring Boot JPA LEFT JOIN in 3 tables - java

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)

Related

Cannot return boolean using JPQL in Spring

I have the following JPQL query in my repository and when I run its SQL version (our database is PostgreSQL), it works properly. However, when I run this JPQL, it returns only the records that has True value. I think the problem may be related to JPQL and wanted to ask. So, is there any problem regarding to this query?
#Query("SELECT p.uuid as uid, " +
"CASE WHEN m.uuid IS NOT NULL THEN true ELSE false END as d FROM Product p " +
"LEFT JOIN Menu m on m.productUuid = p.uuid ")
List<ProductMenu> findAllProduct();

one 2 many jpa qry with join

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"

finding latest entry by JPA

I find this thread very helpful, but it looks like implementation in the advices are not quite efficient because of the nature of JPA.
I am looking for a solution to pickup latest entry of joining query with grouping, implemented by JPA, so it is not a simple job. My implementation is put "ORDER BY time DESC" in the end and pick up the first from return collection, instead of using MAX() function which have to introduce subquery as well, but I wonder is this a good alternative ?
This is the complex query I made by the example from the other example:
"SELECT oo FROM Order AS oo WHERE oo.id IN " +
"(SELECT temp.id FROM " +
"(SELECT t.order.id AS id, MAX(t.order.orderTime) AS ordTime FROM Transaction t " +
"WHERE t.order.name= :name " +
"GROUP BY t.order.name) AS temp" +
")";
This is the query which I think could be a good alternative but not sure:
String query = "SELECT t.order FROM Transaction AS t " +
" WHERE t.order.name= :name " +
" ORDER BY t.order.orderTime DESC";
// and simply just pick up the 1st as the latest entry from result:
Order order = em.createQueryquery , Order .class).getResultList().get(0);
Problem with your solution is that it will load ALL entries in a list for you to select one. As per this answer, you need to limit result to 1 by calling query.setMaxResults(1). Other than that, it is a perfectly fine solution. You can also use query.getSingleResult() to get single entity, but beware of NoResultException if there are no such records.

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