In Spring Data is it possible to turn off Query Generation from method names?
Given the interface
public interface UserRepository extends Repository<User, Long> {
List<User> findByEmailAddressAndLastname(String emailAddress, String lastname);
}
I would want spring security to produce an error saying that generating queries from method names has been turned off please use the explicitly @Query annotation like so.
public interface UserRepository extends Repository<User, Long> {
@Query("select u from User u where u.emailAddress = ?1 and u.lastname = ?2")
List<User> findByEmailAddressAndLastname(String emailAddress, String lastname);
}
I want to turn off the the automatic query generation because I think it is easier to read the query and know what is going on rather than reading the method name and translating to what is the query that Spring data will generate, also on a large team with lots of developers some who might not yet be familiar with spring data @Query is a lot more readable?
How to turn off Query creation from method names in Spring JPA?
You can specify the query-lookup-strategy
on the repositories
tag in the configuration.
<repositories query-lookup-strategy="use-declared-query"/>
See the documentation
User.java
@Entity
@NamedQuery(name="User.findByEmailAddressAndLastName",
query="select u from User u where u.emailAddress = ?1 and u.lastname = ?2")
public User{
}
UserRepository.java
public interface UserRepository extends Repository<User, Long> {
List<User> findByEmailAddressAndLastname(String emailAddress, String lastname);
}
How Spring handles this is called the Query Lookup Strategy. Queries can be resolved by method names (CREATE
), by manual queries (USE_DECLARED_QUERY
), or both (CREATE_IF_NOT_FOUND
) which defaults to method names if no manual query is found. USE_DECLARED_QUERY would give you the desired functionality, warning you if no manual query is specified.
As Kevin answered, this can be configured in xml. But as a more modern option, you can specify the lookup strategy when configuring your repository in a Java Config class with queryLookupStrategy
parameter in the @Enable{store}Repositories
annotation.
For example, to force manual queries, you could use the following:
@EnableJpaRepositories(queryLookupStrategy=QueryLookupStrategy.Key.USE_DECLARED_QUERY)
public class MyDatabaseConfig {
...
}
More info here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With