I am wondering how does Spring JPA derive queries from methods. As an example, if I was to type
interface CarRepo extends CrudRepository<Car, Long>{ findByCarMake(Make make) }
my query would be automatically derived from the method and would be something as "SELECT * from Car WHERE carMake = xxxxx"
I do understand this concepts but I would like to understand how it works behind the scenes. So, how does it actually derive a query from the method name?
I am aiming at creating a similar thing to suit our needs for a NestJs project so in Typescript not Java and also for an..."unorthodox" database which does not have such support out of the box( Neo4J).
I ll be very grateful to whom can and will help me.
CodePudding user response:
Spring Data JPA derives the queries from the method names in your repository.
There are certain keywords that are reserved by Spring. One the one hand, there are query subject keywords like findBy
, existsBy
, countBy
, etc. which influence the return type of the method. On the other hand, there are operators like and
, or
, isIn
, between
, etc. that are applied to the actual query logic.
You start your query with a query subject keyword like findBy
and then the fields of your entity (and optionally operators and more fields). You can even have nested fields like findByProviderName
where your entity has a field provider
which has a field name
. If you define an invalid property or property path (e.g. findByProviderNamw
), your Spring Boot application would fail on startup. You can find more about defining query methods in the official spring reference.
CodePudding user response:
Spring Data using part tree JPA queries
, than map them into SQL query by pre-defined parts.