spring data jpa pagination with sub query not woking - java

below is the query which is working fine
#Query("SELECT city.id as id,city.latitude as latitude, city.longitude as longitude, \n" +
"(SELECT cityTrans.name " +
" FROM city.listOfCityTrans as cityTrans " +
" WHERE cityTrans.languageId=:languageId AND cityTrans.cityId=city.id)" +
" AS name, \n" +
"(SELECT provinceTrans.name " +
" FROM city.province AS province JOIN province.listOfProvinceTrans AS provinceTrans " +
" WHERE provinceTrans.languageId=:languageId AND provinceTrans.provinceId=city.provinceId)" +
" AS provinceName, \n" +
"(SELECT countryTrans.name " +
" FROM city.province AS province JOIN province.country.listOfCountryTrans AS countryTrans " +
" WHERE countryTrans.languageId=:languageId AND countryTrans.countryId=city.provinceId)" +
" AS countryName, province.id as provinceId,province.countryId as countryId \n" +
" FROM City as city")
Page<CitySummary> findCities(#Param("languageId") Integer languageId, Pageable pageable);
but when i pass sort param ?sort=name
then it is creating wrong query
SELECT city.id as id,city.latitude as latitude, city.longitude as longitude,
\n(SELECT cityTrans.name FROM city.listOfCityTrans as cityTrans WHERE
cityTrans.languageId=:languageId AND cityTrans.cityId=city.id) AS name,
\n(SELECT provinceTrans.name FROM city.province AS province JOIN
province.listOfProvinceTrans AS provinceTrans WHERE
provinceTrans.languageId=:languageId AND
provinceTrans.provinceId=city.provinceId) AS provinceName, \n(SELECT
countryTrans.name FROM city.province AS province JOIN
province.country.listOfCountryTrans AS countryTrans WHERE
countryTrans.languageId=:languageId AND
countryTrans.countryId=city.provinceId) AS countryName, province.id as
provinceId,province.countryId as countryId \n FROM
com.pro.api.model.City as city order by cityTrans.name asc
^
can anyone tell why this is happening?

I think the MVC to JPA path only works for entity definitions, not Object[] results, so if your City entity doesn't have a name property, then JPA would try to find another field match, which would be the cityTrans

Related

How to format Date in JPA query

I have a SpringBoot application where I use Repository class to query my Oracle DB table.
Here is how the query and associated function are defined :
#Query( value =" SELECT status "+
" FROM tb1 " +
" WHERE " +
" to_date(cob_Date,'dd-MON-yy') = to_date(:cobDate,'yyyy-mm-dd') " +
" AND business_Day ='BD3' " +
" AND intra_day ='INTRA_06' " +
" AND datasource_name =:datasource" +
" AND upper(status) = 'COMPLETED' " +
" AND frequency = 'MONTHLY' " +
" AND processed = 'Y' " +
" ORDER BY create_date desc FETCH FIRST 1 rows only"
, nativeQuery=true)
List<String> getImpalaJobStatus(#Param("intraDay") String intraDay,
#Param("businessDay") String businessDay,
#Param("cobDate") LocalDate cobDate,
#Param("datasource") String datasource);
If I run this query in SQL developer then I am getting my results back, however if I run it from my SpringBoot Application it returns nothing.
I suspect I am doing something wrong with the Date field "COB_DATE" and this clause under WHERE:
" to_date(cob_Date,'dd-MON-yy') = to_date(:cobDate,'yyyy-mm-dd') " +
I tried it as :
" cob_Date =:cobDate "
but it didn't work either.
That cobDate is being declared as a LocalDate in the method signature implies that you already have that value in date format. If so, then the call to to_date() in the query is not needed. Try binding the LocalDate value directly:
#Query( value =" SELECT status "+
" FROM tb1 " +
" WHERE " +
" to_date(cob_Date,'dd-MON-yy') = :cobDate " +
" AND business_Day ='BD3' " +
" AND intra_day ='INTRA_06' " +
" AND datasource_name =:datasource" +
" AND upper(status) = 'COMPLETED' " +
" AND frequency = 'MONTHLY' " +
" AND processed = 'Y' " +
" ORDER BY create_date desc FETCH FIRST 1 rows only"
, nativeQuery=true)
List<String> getImpalaJobStatus(#Param("intraDay") String intraDay,
#Param("businessDay") String businessDay,
#Param("cobDate") LocalDate cobDate,
#Param("datasource") String datasource);
Note that your Oracle JBDC driver should know how to marshall the LocalDate value to the database such that the query works.

Remove exception No entity found for query

I use this code to make SQL request to find DB record:
public Optional<Subscription> findSubscriptionsByUserEmail(String email) {
String hql = "SELECT s " +
"FROM " + Subscription.class.getName() + " s " +
"INNER JOIN " + Orders.class.getName() + " o ON s.orderId = o.id " +
"INNER JOIN " + Users.class.getName() + " u ON u.id = o.userId " +
"WHERE u.email = :email " +
"ORDER BY s.createdAt DESC ";
TypedQuery<Subscription> query = entityManager.createQuery(hql, Subscription.class).setMaxResults(1).setParameter("email", email);
Optional<Subscription> subscription = Optional.of(query.getSingleResult());
return subscription;
}
But when I don't have a record I get exception: No entity found for query
Do you know how I can skip this exception and continue code execution?
The simplest way to do it is either to try/catch the optional object to see there has been a data sent back or make simple check to see if the optional has an object in it.
Eg:
!subscription.isPresent()? null:subscription;

MySQL Deletion Query, Multiple Inner Joins

I want to delete an "order" from my database using the primary key, orderID. The orderID is a foreign key in orderItem, OrderItem has a foreign key in foodItem called foodItemID, foodItem has a foreign key in menu called menuID.
Below is my query:
"DELETE FROM orders, orderitem, fooditem, menu " +
"USING orders " +
"INNER JOIN orderitem " +
"WHERE orderID = " + "'" + orderID + "' " + " AND orders.orderID = orderItem.orderID " +
"INNER JOIN foodItem " +
"WHERE orderItem.foodItemID = foodItemID.foodItemID " +
"INNER JOIN Menu " +
"WHERE foodItem.menuID = menu.menuID";
I am coding in JAVAFX..
The error I receive is:
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN foodItem WHERE orderItem.foodItemID = foodItemID.foodItemID INNER JOI' at line 1
You don't join WHERE, you join ON something. So
"DELETE FROM orders, orderitem, fooditem, menu " +
"USING orders " +
"INNER JOIN orderitem " +
"ON orderID = " + "'" + orderID + "' " + " AND orders.orderID = orderItem.orderID " +
"INNER JOIN foodItem " +
"ON orderItem.foodItemID = foodItemID.foodItemID " +
"ON JOIN Menu " +
"ON foodItem.menuID = menu.menuID";
Also, this part
"ON orderID = " + "'" + orderID + "' " + "
Is a SQL Injection waiting to happen. You should use prepared statements instead. How you use them depends on what library/framework you're using to connect to the db (which you didn't specify).

Pageable in JPA native query

I want to use pagination with a native query. I use for this this syntaxe as in this example : Spring Data and Native Query with pagination
and it's my query:
#Query(value="SELECT rownum() as RN, users.num, users .l_service,service.type_service, users.date, " +
"chambre.price," +
"price* ( case when(datediff(day,date_d,date_f)=0) then 1 " +
"else datediff(day,date_d,date_f) end ) as Montant," +
"case when (service.type_service='R') and datediff(day,date_d,date_f) >=21 " +
"then (21300+(datediff(day,date_d,date_f)-21)*200)" +
"else price*(case when(datediff(day,date_d,date_f)=0) then 1 else datediff(day,date_d,date_f)end) end AS Montant_final " +
" users.year, users.Etat, " +
" from chambre JOIN users ON chambre.code = users.type " +
"JOIN service on service.code = users.l_service " +
" WHERE users.Etat='V' and RN between ?#{ #pageable.offset -1} and ?#{#pageable.offset + #pageable.pageSize order by users.num",
countQuery ="select count(*) from users ",nativeQuery = true)
Page<Object> getStatistiques(Pageable pageable);
I get this error :
Cannot mix JPA positional parameters and native Hibernate positional/ordinal parameters
This is the solution I found to my problem:
#Query(value="SELECT * from (SELECT ROW_NUMBER() OVER (ORDER BY users.num) as RN, users.num, users .l_service,service.type_service, users.date, " +
"chambre.price," +
"price* ( case when(datediff(day,date_d,date_f)=0) then 1 " +
"else datediff(day,date_d,date_f) end ) as Montant," +
"case when (service.type_service='R') and datediff(day,date_d,date_f) >=21 " +
"then (21300+(datediff(day,date_d,date_f)-21)*200)" +
"else price*(case when(datediff(day,date_d,date_f)=0) then 1 else datediff(day,date_d,date_f)end) end AS Montant_final " +
" users.year, users.Etat, " +
" from chambre JOIN users ON chambre.code = users.type " +
"JOIN service on service.code = users.l_service " +
" WHERE users.Etat='V') AS STA where RN between ?#{ #pageable.offset -1} and ?#{#pageable.offset + #pageable.pageSize} order by STA.num",
countQuery ="select count(*) from users ",nativeQuery = true)
Page<Object> getStatistiques(Pageable pageable);
I share it with you perhaps it can help someone else!

JPA Query to handle NULL Value parameters

i want to select rows from a table in JPA, my query paramter could be null.
So if it is null i want to consider all values for that attribute in that table.
Here is my code :
#Query("SELECT art FROM ArtWork art INNER JOIN art.subjects subject "
+ "INNER JOIN art.styles style "
+ "INNER JOIN art.collections collection "
+ "INNER JOIN art.priceBuckets priceBucket "
+ " WHERE ((subject.title) in (:subjectList) "
+ "AND (style.title) in (:styleList)"
+ "AND (collection.title) in (:collectionList)"
+ "AND (priceBucket.title) in (:priceBucketRangeList)"
+ "AND (art.medium is NULL OR art.medium = :medium)"
+ "AND (art.orientation) LIKE:orientation)"
+ ")")
In the code if :medium is null then i want it search on all mediums in the table
Thanks

Categories