Spring JPA - Issue while sorting on non entity column - spring

I have requirement where I need to get the records based in join of three table with pagination(addition requirement are also there). So I have written a nativeQuery to get the records. Below is the sample query
#Query(value = "SELECT "
+ "a.GROUP_REF_ID as refId "
+ "count(case when c.STAT_CD in :userStatus then (c.grp_user_id) end) as numberOfUsers, "
+ "count(case when b.STAT_CD in :itemStatus then (b.grp_item_id) end) as numberOfItems "
+ "from grp a left join grp_item b on a.grp_id=b.grp_id left join grp_user c on a.grp_id=c.grp_id "
+ "where a.stat_cd in :status and a.co_id in :cids "
+ "group by a.GROUP_REF_ID,a.grp_nam,a.GRP_DESC,a.co_id,a.co_nam,a.CRTE_BY, "
+ "a.CRTE_DT,a.UPDT_BY,a.UPDT_DT ", countQuery = "select count(*) from grp where stat_cd in :status and co_id in :cids ", nativeQuery = true)
public Page<Object> findByStatusAndCompanyIdIn(#Param("status") String status, #Param("cids") List<Long> companyIds,
#Param("userStatus") List<GroupUserStatus> userStatus,
#Param("itemStatus") List<GroupItemStatus> itemStatus, Pageable pageable);
Now the requirement is also that these records are to be sorted on any of the column in select part. So, if user passes numberOfItems, the records are to be sorted on it. But I am facing an issue here because if I pass Sort parameter as numberOfItems, spring prepends an a. before numberOfItems which results in error that not able to find a.numberOfItems.
Is there a way I can stop spring from prepending table alias while creating a query with Sort, or should I write my logic in a different approach

Making my comment an answer so the question can be marked as answered:
Wrap the whole select in another one: select * from (<your current select>) x

I have solved the issue by creating a projection. (Kotlin was used but you’ll get the gist.)
class ShowRepository : JpaRepository<Int, Show> {
#Query("SELECT s AS show, (CASE WHEN (s.status = 'scheduled') THEN s.scheduledStartTime ELSE s.startTime END) AS time FROM Show s")
fun findShows(pageable: Pageable): Page<ShowWithTime>
}
interface ShowWithTime {
val show: Show,
val time: Date?
}
This allows Spring-Data to work its full magic, and using Sort.by(Order.desc("time")) works like a charm.
I’ve written it up with a little bit more detail here: Sorting by a Non-Entity Field.

Related

JPQL and Enum. If you need any Enum

I have a JPQL query that includes several filters and sorting at once.
#Query("SELECT rest FROM Restaurant rest LEFT JOIN rest.votes vote " +
"WHERE (rest.name LIKE concat('%', :searchQuery, '%') OR rest.address LIKE concat('%', :searchQuery, '%')) " +
"AND rest.cuisine = :cuisine " +
"GROUP BY rest.id ORDER BY COUNT(vote.id) DESC")
Page<Restaurant> findAllSortedByRating(#Param("searchQuery") String searchQuery,
#Param("cuisine") СuisineType cuisine,
Pageable pageable);
}
In the third query line, :cuisine is an Enum. Everything works fine when the user has selected one of the options, but what if he wants to see all the options.
For example, with searchQuery, I simply pass an empty string and get the entire list. Of course, this is not possible with Enum, but maybe there is a way to implement such functionality?
So far, I just made two methods in one of which there is no this line, but this is not beautiful because the code is duplicated.
You could use is null
AND (rest.cuisine = :cuisine or :cuisine is null)
Or you could add СuisineType.ALL
AND (rest.cuisine = :cuisine or :cuisine = com.demo.СuisineType.ALL)

How to query the database based on current day using Hibernate?

I would like to retrieve database items based on the current day.
For that purpose I am trying to use the day() function as explained there and mentioned there.
I have a 'created' date field that is automatically filled when a new item is created in the table. It's configured using a model, like that:
#Column(name = "created", nullable = false)
#CreationTimestamp
private Date created;
I created a couple of items and the date is filled in the database as expected.
Now I am trying to call those items using a HQL query:
String hql = "" +
"FROM Item as item " +
"WHERE item.itemId = ?1" +
"AND item.created = day(current_date())";
The problem is that this query is returning a NoResultException.
It's weird because I am using the current_date() function in other scenarios, e.g.:
String hql = "" +
"FROM Item as item " +
"WHERE item.itemId = ?1" +
"AND item.createdAt >= current_date - ?2";
And it is working pretty well!
So I assume the issue is related with day() function.
Try use this:
String hql = "" +
"FROM Item as item " +
"WHERE item.itemId = ?1" +
"AND date(item.created) = current_date()";

Spring Data - Custom DTO Query with filtering

I have a complexe application and I need to retrieve and filter 1000~5000 object for an xls export. Each object having multiple eager relationship (I need them for the export).
If I retrieve all the objects and their relationship as it is, I got some stackoverflow error.
Generaly when I need to make a big export, in order to make it efficient I use a DTO object with an #Query like this :
public interface myRepository extends JpaRepository<Car, Long> {
#Query("SELECT new com.blabla.myCustomObject(p.name, p.surname, c.model, c.number ...) "
+ "FROM Car c "
+ "LEFT JOIN c.person p "
+ "WHERE ... ")
List<myCustomObject> getExportCustomObject();
}
The problem is that the #Query is static and I want to add dynamic filter to my Query (Specifications, Criteria or some other system...)
How to do it ?
Specification cannot be used because this is only the where clause.
But you can use Criteria API. Here's an example. The BasicTeacherInfo is the DTO:
CriteriaQuery<BasicTeacherInfo> query = cb.createQuery(BasicTeacherInfo.class);
Root<Teacher> teacher = query.from(Teacher.class);
query.multiselect(teacher.get("firstName"),teacher.get("lastName"));
List<BasicTeacherInfo> results = em.createQuery(query).getResultList();
You can use #Param annotation to pass dynamic values to HQL, something like:
#Query("SELECT new com.blabla.myCustomObject(p.name, p.surname, c.model, c.number ...) "
+ "FROM Car c "
+ "LEFT JOIN c.person p "
+ "WHERE c.status = :status AND p.name = :name")
List<myCustomObject> getExportCustomObject(
#Param("status") Integer status,
#Param("name") String name
);
Below is one of the possible way where you can try to add offset and limit into your query you can make it dynamic with the help off placeholders.
Below is an sample pseudo code for reference:
Dao Layer:
#Query(value="SELECT e FROM tablename e WHERE condition_here ORDER BY e.id offset :offset limit:limit ")
public returnType yourMethod(String name, int offset, int limit);
Service Layer:
long count = number of records in db.
int a = // number of records to be fetched on each iterations
int num_iterations = count % a ;
int additionalrecords = count / a;
int start= 0;
while(num_iterations>0)
{
dao.yourMethod(start,a);
start = start+a;
count--;
// write your data to excel here
}
dao.yourMethod(start,additionalrecords);
Hope it is helpful.

How to perform left join in hql to fetch data

I am using following query to get data data database
String hql = "from Parameters s "
+"left join fetch s.userValues as uv "
+ "where s.groupId=:gid "
+"and uv.user.id=:uid " ;
Above is my hql query here I am fetching data from Parameter and from userValues.
This query is working properly if user have any value in userValues.
This query is not fetching any value when there is no saved value for user in userValues.
My problem is Whether there should be data in userValues or not I want to fetch data from Parameters.
How to achieve this using hql?
I just want to do left join in hql to get first table values.
You probably want something like this. You need to left join the association to user also. Note that you should use the Hibernate mapping between Parameter and Group as below. But you will probably need to use grouping to remove duplicate results.
String hql = "from Parameters s "
+ "join s.group g "
+ "left join fetch s.userValues uv "
+ "left join uv.user u "
+ "where g.id=:gid "
+ "and (u.id=:uid or u is null) ";

Spring Data JPA Repository returns Object[] instead of MyType while using Sum Function

Until today I was using this statement:
#Query(value = "select top 5 p.*, sum(po.quantity) as total_quantity from product p " +
"inner join productorder po " +
"on p.id = po.product_id " +
"group by p.id, p.name " +
"order by total_quantity desc", nativeQuery = true)
List<Product> findTopFiveBestSellerNative();
Here as i define the return type as a list of Products, i exactly get what i need. And the selected column total_quantity is simply ignored.
Lastly i needed to integrate pagination into this query. Since Spring does not support pagination handling with native queries, i wanted to first transform this query to JPQL (then i will add pagination). And now it looks like this:
#Query(value = "select p, sum(po.quantity) as total_quantity " +
"from Product p, ProductOrder po " +
"where p.id = po.pk.product " +
"group by p.id, p.name " +
"order by total_quantity desc")
List<Product> findTopFiveBestSeller();
The return type is now a list of object arrays, where the first element of array is Product, and second one is the total_quantity. (Although the method signature says List..)
How can i change my statement or somehow achieve this, so that i do not have to deal with array, and simply just get my Product objects?
EDIT: I had the idea to use this query as a subquery, and just select the products from the subquery. It turns out that the JPQL cannot do subqueries in the 'from' clause..
Fact is your query is not returning only the columns needed to build a Product object, so Spring JPA is mapping it to an object.
Create an aggregate entity that extends product and that contains the property totalQuantity and map your query to it (possibly in another repository)

Resources