Dynamic query with Spring Data JPA and Search by Example of

Search all around!

The Problem 😠

The problem was simple, the query to the database should be based on the values supplied from the front-end. Sometimes the user would select or enter all the values or it is search based on certain values. Child’s play right 😎. Then without second thought created a repository and was stuck when its time to type in the query method. Wait what how would write the query methods.

I know i was doomed when the google forced me to head to the 2nd page of its search results 😯 and criteria api was the appropriate solution. It would do wonders for small set of vales to be queried on.

Checkout the complete code @ GitHub 💻

The Situation 😕

Lets consider a car catalog database with Make, Model and year of release.

So implementing criteria api will be easy with with few CriteriaObjects methods and done!, add!, commit!, push!. Ready for prod ⏳.

Lets spice it up, the POJO is added with some more properties lets say Horse Power, Turning Radius and lot more stuff which are to stored in database and we are again making up the changes with CriteriaObjects and its results in cycle for every new change.

To the rescue 👍

Here comes Query by Example to save us. It allows dynamic query building at runtime without specifying query fields. Just pass in the POJO, let JpaRepository handle it for you and problem solved.

Example.of also takes an matcher object where in we can specify to which columns we can ignore the case and search.

Time to Search ⏰

Let say we wanna search all the cars from the year 2015, all we have to do is pass the json with parameters.

Next search is by make and year

Limitations 🔐

We cannot query for conditions like between two ranges, example car make year between years 2010 to 2020.

Reference and Documentations 📕




Java Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How I Make an Extra $1,344 Passive Income a Month Online —Even Though I Started Out Clueless

Writing faster C++ and python code for competitive programming, using vscode

Day 20 of July LeetCode Challenge

Step by step guide of “How to claim your DNS domain on ENS”

On Becoming A World-Class Developer.

How to change a str to Upper case?

HTML5 Template — The Perfect Thing for Web Development

Building the World’s Largest Project Learning Platform Using Blockchain Smart Contracts.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Naveen Kumar M N

Naveen Kumar M N

Java Developer

More from Medium

Liquibase — Exploring with Spring boot and Maven

JPA Search using Spring Data Example

Different calling forms of REST services with Feign client in Spring Cloud