Reputation: 8606
I'm new to Spring Boot, so I have a couple of basic questions.
When we define a Repository interface which extends JpaRepository
@Repository
public interface UserInfoRepository extends JpaRepository<UserInfo, Long> {
Optional<UserInfo> findByEmail(String email);
List<UserInfo> findAllByEmail(String email);
}
These methods can be called from Service class (we probably don't even need to mention these two methods). So far, all's well and good.
Questions:
How is the method findByEmail
defined? And how's it called behind the scenes?
What if we want to add a custom method findUserAction
with native SQL? In that case, we'll need to declare it in interface UserInfoRepository
and define it in a UserInfoRepositoryImpl
class. In that case, won't we need to define the other existing methods too?
Any help would be appreciated. Thanks in advance! :)
Upvotes: 2
Views: 3726
Reputation: 81988
There are different ways how Spring Data allows you to define query methods. Ordered by the amount of work you have to do (and also the flexibility you get):
Predefined methods. Depending on what interface you choose as the basis of your repository you get a bunch of methods for free: those that are declared in the interface. You have CrudRepository
, PagingAndSortingRepository
, JpaRepository
, QueryByExampleExecutor
and JpaSpecificationExecutor
as choices. The methods of these interfaces are implemented in classes that are part of Spring Data. For example in SimpleJpaRepository
.
Query Derivation. Here you can just declare a method with a specific naming scheme. Spring Data will parse the method name construct a query from that, bind your arguments and execute it. The query is created using the Jpa Criteria API.
Query annotation/Named queries. You can provide the query yourself, by adding a @Query
annotation or by declaring a named query on the entity or by putting it in a property file. Spring Data will find it and execute it. It will also add nifty stuff in order to add pagination and it will process your arguments through a SpEL if you choose to use those.
Finally you may provide your own implementation where you might do what ever Java allows you to do: query the database using the EntityManager
or the JdbcTemplate
, not accessing the database at all but doing something completely different.
In general the whole thing works like this: If a repository is to be injected Spring Data creates a proxy implementing all the methods declared in your repository. In that proxy Spring Data will analyse the method call, decide which of the cases above applies and execute it. Actually the deciding what process to use is done at start up, but that shouldn't matter for understanding it.
All these strategies to implement a method are independent of each other, so you can use different strategies for each method in a repository.
Upvotes: 4