Last active
June 5, 2019 09:13
-
-
Save FrancescoJo/5e285f38d2caf253cedb34a747d897f1 to your computer and use it in GitHub Desktop.
How to disable spring-jpa automatic method derivation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface UserRepository : JpaRepository<User, Long>, UserRepositoryExtension | |
interface UserRepositoryExtension { | |
/* | |
* Here we get exception as following: | |
* | |
* Caused by: java.lang.IllegalArgumentException: Failed to create query for method | |
* public abstract User UserRepositoryExtension.getByRoleCriteria(java.lang.String,java.util.Set)! | |
* At least 2 parameter(s) provided but only 1 parameter(s) present in query. | |
* | |
* at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:84) | |
* ... <14 internal calls> | |
* at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.mapMethodsToQuery(RepositoryFactorySupport.java:561) | |
* ... <11 internal calls> | |
* ... 31 common frames omitted | |
* Caused by: java.lang.IllegalArgumentException: At least 2 parameter(s) provided but only 1 parameter(s) present in query. | |
* at org.springframework.util.Assert.isTrue(Assert.java:136) | |
* at org.springframework.data.jpa.repository.query.QueryParameterSetterFactory$CriteriaQueryParameterSetterFactory.create(QueryParameterSetterFactory.java:291) | |
* ... <25 internal calls> | |
* ... 57 common frames omitted | |
* | |
* This error is fixed when we name this method as `getByNameAndRoles`, but we do not want that. | |
* | |
* Spring Automatic name derivation rule: | |
* https://docs.spring.io/spring-data/jpa/docs/2.0.7.RELEASE/reference/html/#repositories.query-methods.query-creation | |
*/ | |
@Nullable | |
fun getByRoles(name: String, roles: Set<Role>): User? | |
} | |
@Repository | |
class UserRepositoryExtensionImpl : UserRepositoryExtension { | |
@PersistenceContext | |
private lateinit var em: EntityManager | |
override fun getByRoles(name: String, roles: Set<Role>): User? { | |
val roles = roles.map { "\'${it.name}\'" }.joinToString() | |
val sql = """ | |
SELECT u | |
FROM User u | |
WHERE u.name = $name | |
AND u.roles IN ($roles) | |
""" | |
TODO("Not implemented") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment