Background
Datatable item
:
+---------+---------+--------+
| field | type | index |
+---------+---------+--------+
| id_item | INT | PK |
| name | VARCHAR | UNIQUE |
+---------+---------+--------+
ItemRepository.java
:
public interface ItemRepository extends CustomRepository<Item, Integer> {
public Item getByName(String name); // because of the unique index
}
CustomRepository.java
:
@NoRepositoryBean
public interface CustomRepository<E, PK extends Serializable> extends PagingAndSortingRepository<E, PK>, JpaSpecificationExecutor<E> {
// common methods
}
CustomRepositoryImpl.java
:
public class CustomRepositoryImpl<E, PK extends Serializable> extends SimpleJpaRepository<E, PK> implements CustomRepository<E, PK> {
// common methods implementations
}
Question
As you can see, there isn't no implementation of the interface ItemRepository
. Which means, the getByName
method has just a signature and never get implemented at anywhere. But it works. How?
PS
For the skeptics, with Eclipse, when keeping Ctrl pressed and the mouse over the getByName
signature, clicking on Open Implementation
doesn't open any JAVA file at all.
Spring uses AOP for repositories, and will intercept any getByX
method where X
matches a bean property. In your example, the Item
bean, declares the name
property, so Spring intercepts it for you.
See Defining query methods in the Spring Data JPA manual.