xing
xing

Reputation: 484

Questions for JPA repository example in Spring in Action 4th edition

Around Page 325:

SpitterRepository extends JpaRepository.
SpitterRepositoryImpl implements SpitterRepository. Also SpitterRepositoryImpl extends SpitterSweeper interface. 
    public interface SpitterSweeper{
        int eliteSweep();
    }

It says the eliteSweep method should be declared in the SpitterRepository interface. So do not quite understand it, why can't we only declare it in the eliteSweep interface?

Upvotes: 0

Views: 121

Answers (1)

Nikolay Rusev
Nikolay Rusev

Reputation: 4230

from their doc:

The repository proxy has two ways to derive a store-specific query from the method name. It can derive the query from the method name directly, or by using an additionally created query. Available options depend on the actual store. However, there's got to be an strategy that decides what actual query is created. Let's have a look at the available options.

The query builder mechanism built into Spring Data repository infrastructure is useful for building constraining queries over entities of the repository. The mechanism strips the prefixes find…By, read…By, and get…By from the method and starts parsing the rest of it. The introducing clause can contain further expressions such as a Distinct to set a distinct flag on the query to be created. However, the first By acts as delimiter to indicate the start of the actual criteria. At a very basic level you can define conditions on entity properties and concatenate them with And and Or .

this means, that Spring Data JPA will construct query from method name and for simple queries, you don't need to write jpql/hql queries, spring data jpa will automatically create them. Spring data jpa will parse method name and will build the needed query.

as for why are declared in interface? the framework will try to create a repository proxy instance, concrete implementation of this interface which will be used where you inject this interface.

Upvotes: 1

Related Questions