Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic search query using JpaRepository

I have a "Product" entity with "id" "productName" and "price"

I implement a server side pagination and filter with angular ng-table.

My client send a json like

"{"page":1,"sort":"DESC","orderBy":"productName","filter":{"productName":"test","price":300}}"

but could be like that

"{"page":1,"sort":"","orderBy":"","filter":{}}"

How can I implement this kind of dynamic query wit jpaRepository

query = "select * FROM products WHERE 1=1 "
for (Map.Entry<String, String> filter : filters.entrySet()) {
    String key = filter.getKey();
    String value = filter.getValue();
    query+= "AND " + " LIKE %" + value + "% "
}

if(!orderBy.isEmpty())
{
  query.="ORDER BY " + orderBy + " ";
}
etc.

my IProductRepository.java

public interface IProduitRepository extends JpaRepository<Product, Long> {
    @Query("select p from Produit p where p.price = :x")
    public Page<Product> customFindByPrice(@Param("x") String name,Pageable p);

    public Page<Product> findByPrice(double price, Pageable p);
}

So how can I implement my dynamic searsh query with JpaRepository ?

I know about predicate but I don't really understand how to use them in my case

like image 1000
amdev Avatar asked May 15 '26 23:05

amdev


1 Answers

You could use Elastic Search as fastest search engine. And for the formation of query I would strongly suggest using SerchQueryParser: https://www.npmjs.com/package/search-query-parser.

like image 174
Slavcho Avatar answered May 17 '26 13:05

Slavcho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!