Spring Data Mongodb #Query with pagination - spring

Is there any way to write some query to mongo with #Query annotation and add paginaiton right into it. I have a method in repository
#Query("{'customer._id' : ?0 }")
List<Order> findOrderByCustomerName(String customerName);
and i want it to looks smth like this
#Query("{'customer._id' : ?0 }.skip{(?1 - 1) * ?2}.limit(?2)")
List<Order> findOrderByCustomerName(String customerName, int page, int size);
Is there any way to to it?

You can add Pageable as a parameter.
#Query("{'customer._id' : ?0 }")
List<Order> findOrderByCustomerName(String customerName, Pageable pageable);

Related

Spring boot repository query to return a ordered result

public interface StudentRepository extends MongoRepository<Student, String> {
Page<Student> findByIdInAndNameLike(List<String> ids, String name, Pageable pageable);
}
In Service layer :
Pageable pageable = PageRequest.of(page, size);
studentRepository.findByIdInAndNameLike(idList, name, pageable );
Here this idList is an ordered list. And I need to get the search results according to the order of that idList.
eg : List<String> idList= Arrays.asList("123", "111", "213");
So here the Student with id 123 should come first. And student with id 213 should come last.
As per this tutorial u have to provide the 3rd parameter to PageRequest which exactly does the sorting for you
Pageable sortedByName = PageRequest.of(page, size, Sort.by("id"));

#Query Annotation in Spring Cassandra Repository not working

I am trying to use #Query Param for Cassandra repository in Java Springboot.
But its not working. Below is the sample code.
#Repository
public interface Table1Repository extends CassandraRepository<Table1,TransactionKey>{
#Query("SELECT * FROM table1 WHERE code=?0 and product=?1 and id=?2 order by transactiontime DESC limit ?3")
List<Table1> searchTransactionLimit(String code,String product,Double id, int limit);
}
If I hardcode the value of id within the #Query, then its working.
For example,
#Query("SELECT * FROM table1 WHERE code=?0 and product=?1 and id=17.0 order by transactiontime DESC limit ?3")
SO basically, type String and int are working in #Query. But type Double is not working.
You can try as below also but that limit number need to there in method name.
List<Table1> findTop10ByCodeAndProductAndIdOrderByTransactiontimeDesc(String code,String product,Double id);
you can try the below also by pageable.
Pageable pages = PageRequest.of(0, limit);
findByCodeAndProductAndIdOrderByTransactiontimeDesc(String code,String product,Double id,Pageable pages );

Spring Data JDBC - Pageable on custom Query

On my Project I have a Repository that extends CrudRepository. Inside there I have a custom query:
public interface CustomerRepository extends CrudRepository<Customer, Long> {
#Query("select * from person where firstname = :firstname")
List<Customer> findByFirstname(#Param("firstname") String firstname, Pageable pageable);
}
in my Service-Class I try to put the List in a Pageable - Object like:
... getPageableCustomer(String firstname, Pageable pageable){
// => By using "Sol" I got 90 matching entries
List<Customer> custList = customerRepository.findByFirstname(firstname, pageable);
Page<Customer> custPage = new PageImpl<Customer>(custList, pageable, custList.size());
return custPage;
}
the return value includes the complete List "custList". What would be the best way to get a pageable object with specified offset and size?
One option could be to use
customer.subList(fromIndex, toIndex)
but that feels wrong. Also because of Loading all Data inside the list instead of just getting data by size and offset as parameterized with pageable.
Remark: In case of using Page inside the Repository I ´ll get org.springframework.dao.IncorrectResultSizeDataAccessException: Incorrect result size: expected 1, actual 88
There is also a open Improvement on Jira that could be found here:
https://jira.spring.io/browse/DATAJDBC-554?filter=-3
hope for some help...
I got a response on the JIRA-Issue from Dirk Luijk (Thx Dirk :))
https://jira.spring.io/browse/DATAJDBC-554?filter=-3
interface FooRepository extends PagingAndSortingRepository<FooEntity, Long> {
List<FooEntity> findAllByBar(String bar, Pageable pageable);
Long countAllByBar(String bar);
}
And then combining those 2 queries like this:
List<FooEntity> fooList = repository.findAllByBar("...", pageable);
Long fooTotalCount = repository.countAllByBar("...");
Page<FooEntity> fooPage = PageableExecutionUtils.getPage(fooList, pageable, () -> fooTotalCount);
"the mistake in your workaround is your custom query. In Spring Data JDBC 2.0 you don't need to use that, except for special queries but they won't support pageables."
Possible Parameters could be found:
https://docs.spring.io/spring-data/jdbc/docs/current/reference/html/#jdbc.query-methods
Thx Dirk,
I also find a workaround to get it running with a custom Query. Just use limit, offset and orderBy as additional Parameter like so:
#Query("select * from person where firstname = :name order by :order limit :size offset :offset")
List<Customer> findByFirstNameCustomQuery(#Param("name") String name, Pageable page, #Param("offset") long offset,
#Param("size") long size, #Param("order") String order);
And than change the call inside the Service like:
List<Customer> custList = customerRepository.findByFirstNameCustomQuery(firstname, pageable, ....

How to perform sort with multiple fields on custom query JPQL with Spring Pageable

I am using Spring's Pageable to sort the columns.
A working example is below:
Pageable pageable = PageRequest.of(0, countOfBookData.intValue(), getSortingDirection(sortingOrder), sortingField);
Where sortingOrder = ASC and sortingField = bookName
Here is the query
#Query("SELECT bs FROM BookSummary bs WHERE bs.bookId=:bookId")
List<Books> getBookDetails(#Param("bookId") Integer bookId, Pageable pageable)
But I got stuck when I need to perform this sort on Custom my custom query.
So I have no idea how I can perform the sorting using Pageable for below custom query:
Public List<Tuple> getBookDetails(Integer bookId){
String query = "SELECT book.bookCd as bookCode, "
+ "book.name as bookName"
+ "FROM Book book WHERE book.bookId=:bookId";
return entityManager.createQuery(query , Tuple.class).setParameter("bookId", bookId).getResultList();
}
The same as in the first custom query but using the Projection, for example:
public interface BookDetails {
String getBookCode();
String getBookName();
}
#Query("select b.bookCd as bookCode, b.name as bookName from Book b where b.bookId = ?1")
List<BookDetails> getBookDetails(Integer bookId, Pageable pageable);
Note that projection method names must match with corresponding aliases in the query.
Or without the query:
List<BookDetails> getAllById(Integer bookId, Pageable pageable);

Oracle Parallel Hint on Spring Data JPA Specification

Is it possible to use parallel hint on the spring data jpa specification? org.hibernate.jpa.QueryHints package does not contain PARALLEL hint.
I added a comment like in the example below. But I couldn't see the running query.
Calling find method with specifications:
CarSpecifications carSpecifications = new CarSpecifications(car);
List<Car> carList = carRepository.findAll(carSpecifications, pageable);
Repository:
#Override
public Page<T> findAll(Specification<T> spec, Pageable pageable) {
TypedQuery<T> query = getQuery(spec, pageable);
query.setHint("org.hibernate.comment", "Example Comment");
return pageable == null ? new PageImpl<T>(query.getResultList()) : readPage(query, pageable, spec);
}
or in the interface
#QueryHints({ #QueryHint(name = "org.hibernate.comment", value ="Example Comment") })
Page<T> findAll(Specification<T> spec, Pageable pageable);
Thanks.

Resources