1. Overview

Spring Data repositories come with a host of methods that simplify the implementation of the data access logic. Nevertheless, choosing the proper method is not always as easy as we might expect.

One example is the methods prefixed with findBy and findOneBy. Even though they seem to do the same thing based on the names, they’re a little bit different.

2. Derived Query Methods in Spring Data

Spring Data JPA often gets praised for its derived query methods feature. These methods offer a way to derive specific queries from method names. For example, if we want to retrieve data by a foo property, we can simply write findByFoo().

Typically, we can use multiple prefixes to construct a derived query method. Among these prefixes are findBy and findOneBy. So, let’s see them both in practice.

3. Practical Example

First, let’s consider the Person entity class:

@Entity
public class Person {

    @Id
    private int id;
    private String firstName;
    private String lastName;

    // standard getters and setters
}

Here, we’ll be using H2 as our database. Let’s use a basic SQL script to seed the database with data:

INSERT INTO person (id, first_name, last_name) VALUES(1, 'Azhrioun', 'Abderrahim');
INSERT INTO person (id, first_name, last_name) VALUES(2, 'Brian', 'Wheeler');
INSERT INTO person (id, first_name, last_name) VALUES(3, 'Stella', 'Anderson');
INSERT INTO person (id, first_name, last_name) VALUES(4, 'Stella', 'Wheeler');

Lastly, let’s create a JPA repository to manage our Person entity:

@Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {
}

3.1. findBy Prefix

findBy is one of the most used prefixes for creating derived query methods that denote search queries.

The verb “find” tells Spring Data to generate a select query. On the other hand, the keyword “By” acts as the where clause as it filters the returned result.

Next, let’s add a derived query method that gets a person by the first name to our PersonRepository:

Person findByFirstName(String firstName);

As we can see, our method returns a single Person object. Now, let’s add a test case for findByFirstName():

@Test
void givenFirstName_whenCallingFindByFirstName_ThenReturnOnePerson() {
    Person person = personRepository.findByFirstName("Azhrioun");

    assertNotNull(person);
    assertEquals("Abderrahim", person.getLastName());
}

Now that we’ve seen how to use findBy to create a query method that returns a single object, let’s see if we can use it to get a list of objects. To do so, we’ll add another query method to our PersonRepository:

List<Person> findByLastName(String lastName);

As the name implies, this new method will help us find all the objects with the same last name.

Similarly, let’s test findByLastName() using another test case:

@Test
void givenLastName_whenCallingFindByLastName_ThenReturnList() {
    List<Person> person = personRepository.findByLastName("Wheeler");

    assertEquals(2, person.size());
}

Unsurprisingly, the test passes with success.

In a nutshell, we can use findBy to get either one object or a collection of objects.

What makes the difference here is the return type of the query methods. Spring Data decides whether to return one or many objects by looking at the return type.

3.2. findOneBy Prefix

Typically, findOneBy is just a specific variation of findBy. It denotes explicitly the intention to find exactly one record. So, let’s see it in action:

Person findOneByFirstName(String firstName);

Next, we’ll add another test to confirm that our method works fine:

@Test
void givenFirstName_whenCallingFindOneByFirstName_ThenReturnOnePerson() {
    Person person = personRepository.findOneByFirstName("Azhrioun");

    assertNotNull(person);
    assertEquals("Abderrahim", person.getLastName());
}

Now, what happens if we use findOneBy to get a list of objects? Let’s find out!

First, we’ll add another query method to find all Person objects with the same last name:

List<Person> findOneByLastName(String lastName);

Next, let’s test our method using a test case:

@Test
void givenLastName_whenCallingFindOneByLastName_ThenReturnList() {
    List<Person> persons = personRepository.findOneByLastName("Wheeler");

    assertEquals(2, persons.size());
}

As shown above, findOneByLastName() returns a list without any exception being thrown.

From a technical point of view, there is no difference between findOneBy and findBy. However, creating a query method that returns a collection with the prefix findOneBy won’t make sense semantically.

In short, the prefix findOneBy provides only a semantic description for the need to return one object.

Spring Data relies on this regular expression to ignore all the characters between the verb “find” and the keyword “By”. So, findBy, findOneBy, findXyzBy… are all similar.

There are a few key points to keep in mind when creating derived query methods using the find keyword:

  • The important parts of a derived query method are the keywords find and By.
  • We can add words between find and By to denote something semantically.
  • Spring Data decides to return one object or a collection based on the return types of the methods.

4. IncorrectResultSizeDataAccessException

An important caveat to mention here is that both findByLastName() and findOneByLastName() methods throw IncorrectResultSizeDataAccessException when the returned result is not of the expected size.

For example, Person findByFirstName(String firstName) will throw the exception if there is more than one Person object with the given first name.

So, let’s confirm this using a test case:

@Test
void givenFirstName_whenCallingFindByFirstName_ThenThrowException() {
    IncorrectResultSizeDataAccessException exception = assertThrows(IncorrectResultSizeDataAccessException.class, () -> personRepository.findByFirstName("Stella"));

    assertEquals("query did not return a unique result: 2", exception.getMessage());
}

The cause of the exception is that even though we declared our method to return one object, the executed query returns more than one record.

Similarly, let’s confirm that findOneByFirstName() throws IncorrectResultSizeDataAccessException using a test case:

@Test
void givenFirstName_whenCallingFindOneByFirstName_ThenThrowException() {
    IncorrectResultSizeDataAccessException exception = assertThrows(IncorrectResultSizeDataAccessException.class, () -> personRepository.findOneByFirstName("Stella"));

    assertEquals("query did not return a unique result: 2", exception.getMessage());
}

5. Conclusion

In this article, we explored in detail the similarities and differences between findBy and findOneBy prefixes in Spring Data JPA.

Along the way, we explained the derived query methods in Spring Data JPA. Then, we highlighted that despite the different semantic intents between findBy and findOneBy, they’re the same under the covers.

Lastly, we showcased that both throw IncorrectResultSizeDataAccessException if we choose the wrong return type.

As always, the complete code for this article can be found over on GitHub.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.