Query by Example

Learn why custom queries are not enough and a better approach that is query by example.

Why query derivation isn’t enough?

Query derivation and handwritten queries can get us pretty far. That said, what happens when we add a filter option to our site? Do we want to let customers search on various fields they get to choose?

Let’s imagine that we want to add the ability to search based on name. It’s not too difficult. We can create findByName(String name) in our repository and we’re done.

Unfortunately, we keep finding use cases where we need complex searching mechanisms. The customers want it to do partial matches. Again, this isn’t difficult. Adjust that last query to become findByNameContaining(String partialName).

We soon get a new request. Now the customers want us to let customers search by name and description. We can write the query findByNameAndDescription(String name, String description) to do that. Then we should make everything partial and match any case. So, our simple finder morphs into findByNameContainingAndDescriptionContainingAllIgnoreCase(String partialName, String partialDescription).

Not only is that hard to type into a course and our code, it’s also complicated when UX testing shows that people want a radio button to toggle between and and or.

By now, our repository is looking like this:

Get hands-on with 1200+ tech skills courses.