Birdman
Birdman

Reputation: 1524

How does Java Spring query MongoDB?

I'm trying to learn how to connect my Java Spring app to my MongoDB database. I'm following this guide:

https://spring.io/guides/gs/accessing-data-mongodb/

I'm trying to learn the "Create simple queries" section.

package hello;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {

    public Customer findByFirstName(String firstName);
    public List<Customer> findByLastName(String lastName);

}

They show extending the MongoRepository interface and defining certain methods. However these methods are not overrides and are not methods inherited from the interface. It doesn't appear as if they implement these methods anywhere for the actual implementation, so I'm incredibly confused how this works.

"You can define other queries as needed by simply declaring their method signature. In this case, you add findByFirstName, which essentially seeks documents of type Customer and finds the one that matches on firstName."

Here's the repository for the full code for the tutorial: https://github.com/spring-guides/gs-accessing-data-mongodb

I'm incredibly confused how definding a new method in the interface without implementing that method myself magically allows me to construct queries...anyone can shed some light?

Upvotes: 1

Views: 293

Answers (1)

devshawn
devshawn

Reputation: 711

This is a method of constructing queries implemented behind-the-scenes of Spring Data JPA. It definitely looks like magic, but it's Spring's way of hiding the complexity of writing queries. By extending from MongoRepository, Spring automatically creates queries based on the method names you define within your repository interface.

For example, the method public Customer findByFirstName(String firstName) roughly translate to the following query (where $firstName is the firstName variable).

db.Customer.find({firstName : $firstName})

You can see all of the keywords you can use to create queries via method names in the query creation section of the Spring Data JPA documentation.

Upvotes: 1

Related Questions