5 ways to find data with Spring Data

Greg L. Turnquist
5 min readJul 28, 2022

Spring Data provides all kinds of ways to interact with your data store. But do you know them ALL? Odds are, you haven’t seen them all.

And you may be suffering from wasting your time on some queries because of it.

In this article, find out ALL the ways you can access your data, and see which one is for YOU!

1 —Custom finders

The simplest and most eye-catching solution (to me) is your ability to write a custom query WITHOUT WRITING any, well, query, is this:

public interface ItemRepository extends CrudRepository<Item, Long> {
List<Item> findBySku(String sku);
}

In a system where you have defined your Item type, and it has a field tracking its SKU value, you can do that by writing what’s above.

This tactic to craft a custom finder is known as query derivation. Spring Data simply parses the name of the method, sees the “findBy” prefix and also the names of the fields inside Item, and is able to craft a query. It also binds the incoming argument and then fashions the output to work with a standard Java List.

Spring Data also supports return types including Iterable, Stream, Flux, Optional, and more.

But what if you don’t know all the criteria needed to fetch? What if they keep changing? Then check out the next section.

2 — Query by Example

--

--

Greg L. Turnquist

Sr. Staff Technical Content Engineer at CockroachDB • YouTube Content Creator at https://youtube.com/@ProCoderIO • Best-Selling Author • Coffee Lover