How to limit the results of a Spring Repository with custom query - spring

I am using a Spring repository to query a database, but because of the nature of my application I need to use a custom #Query in order to JOIN FETCH lazy collections.
This process works fine, but now I need to limit the result to a single record. I understand that Spring has the notion of findFirst or findTop1 in the method names, but this does not appear to work when you have a custom query.
How can I use a custom query and limit the result to 1 record when using a Spring repository?

you need to pass a Pageable param in your query method
#Query("select e from Entity e LEFT JOIN FETCH e.list")
public Page<Entity> find(Pageable pageable);
and call the method passing the object
repository.find(new PageRequest(0, 1));

Related

Native Query in spring boot JPA

I'm using spring boot 2.6 and spring boot JPA version 2.6.4. I was interested in pull last five records from mysql table by using next query
#Query(value="SELECT * FROM produit p ORDER BY p.id DESC LIMIT 5")
public Collection getProduit();
Normally in the #Query block, i need to add the nativeQuery = true after the value property but the nativeQuery attribute is not defined. What am i missing?
Please help, already 5 hours searching on this.
When using a native query you need to define a mapping of the values to for example your own type. You could use interface based projections when you only need to read data see interface based projections. Then your could would look like
#Query(nativeQuery=true, value="SELECT * FROM produit p ORDER BY p.id DESC LIMIT 5")
Set<Projection> getProduit();
Another thing to check would be what import is used for the #Query annotation, maybe it is the wrong one.

Expose custom query in Spring Boot Rest API with multiple joins

I have an Spring REST Api and a MySQL Database, now I would like to expose the result of an custom query with multiple joins.
I have tried multiple suggestions that I found online but none of them were working for me so far.
What I want to do is something like a read only DTO that has all the fields of my custom query so that in the end I have one api page exposing the DTO data as JSON so my client (Angular) can read the data from there.
I already tried to:
create an #RestController with an injected EntityManager that executes a NativeQuery and then populates the DTO with the returned data but since my DTO is no Entity I get an Hibernate Mapping Exception
create a custom Repository and its Impl but with a similar outcome
place the Query inside an existing #Entity that is part of the Query statement
What am I missing here? Do I have to annotate my DTO maybe? Cuttently it's just a POJO, I think the #Entity annotation is not the right thing here since I don't want a Table created from my DTO.
Fixed it by letting the Query return an Array of type Object and afterwards mapping it to the DTO Constructor.

Pagination in Spring using #RestController, but without using Spring Data Rest Pageable?

I know using Spring Data Rest I can use the in-built functionality of Pagination Like this
Page<Product> findByCategoryId(#RequestParam("id") Long id, Pageable pageable);
However, I am in project I am using Spring mvc #RestController and want to achive the same functionality
I tried like this:-
Session currentSession = entityManager.unwrap(Session.class);
Query<Product> theQuery = currentSession.createQuery("from Product", Product.class);
theQuery.setFirstResult((pageNumber-1) * pageSize); // This is 0 based
theQuery.setMaxResults(pageSize);
List<Product> dataList = theQuery.getResultList();
return dataList;
It works but I don't get the count of total number of records in the table.
And for UI pagination I need that.
So do I have to hit 2 queries everytime first like above then 1 query to fetch record size. (Which can cause data sync problems if records are updated)
Or
Is there a better way to achieve this in SINGLE QUERY
If you need the total number of records then you must create a second query.
You could do that in one query with a subquery but then you cannot use Entities as return type.
Regarding data sync problems: If you run both queries in the same transaction there is no problem.
Btw. why do you unwrap the Hiberante Session? There is no need for that in your example.

Springboot JPA #Query Rest Giving PersistentEntity must not be null

I am trying to put together a simple rest service with springboot 1.4.3. I have it up and running with simple queries like findByRecid, however when I try to do a #Query statement on that same entity, I get the below error message
{"cause":null,"message":"PersistentEntity must not be null!"}
Further, if I use a fully qualified name for the entity in the query, Intellij tells me that the class isn't an entity, even though it's marked with #Entity and works with the standard springboot queries. Please assist if possible - I've been trying to figure this one out for days. Below is the query for your reference
#Query("SELECT new com.test.domain.ReceivableBeans.RecAgeBucketGroupAmountSum(r.agebucket, sum(r.amount)) from com.test.domain.Receivable as r GROUP BY r.agebucket")
List<com.test.domain.ReceivableBeans.RecAgeBucketGroupAmountSum> recByAgeBucket();
Try:
#Query("select new ReceivableStats(r.agebucket, sum(r.amount)) from Receivable r group by r.agebucket")
List< ReceivableStats> recByAgeBucket();
or name your aliases in the query, e.g.
sum(r.amount) as amount
and have your method return an Object[].

jpa pagination suppress count query

We are using Spring Data JPA Repository.
For pagination we are passing the Pageable object to the JPA Repository findBy Methods.
Since in our UI , we are not displaying the total count of records, we don't want the count query to be fired .
Is there any way to suppress the count query fired during pagination ?
Have your repository method return List<Entity> rather than Page<Entity>, and I believe it won't run the count query.
See "Special Parameter Handling" in Spring Data JPA documentation section "1.2.2 Defining query methods".

Resources