DATAJPA-129 - Allow definition of NamedQuery name to be used in @Query.

@Query now has a name attribute that allows defining the NamedQuery name to be used to override the convention based ${domainClass}.${finderMethodName}.
This commit is contained in:
Oliver Gierke
2011-12-03 01:30:53 +01:00
parent c134e10727
commit aef195eaed
3 changed files with 31 additions and 1 deletions

View File

@@ -46,4 +46,10 @@ public @interface Query {
* Configures whether the given query is a native one. Defaults to {@literal false}.
*/
boolean nativeQuery() default false;
/**
* The named query to be used. If not defined, a NamedQuery with name of {@code $ domainClass}.${finderMethodName}}
* will be used.
*/
String name() default "";
}

View File

@@ -158,6 +158,17 @@ public class JpaQueryMethod extends QueryMethod {
return getAnnotationValue("nativeQuery", Boolean.class).booleanValue();
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.QueryMethod#getNamedQueryName()
*/
@Override
public String getNamedQueryName() {
String annotatedName = getAnnotationValue("name", String.class);
return StringUtils.hasText(annotatedName) ? annotatedName : super.getNamedQueryName();
}
/**
* Returns whether we should clear automatically for modifying queries.
*

View File

@@ -56,7 +56,7 @@ public class JpaQueryMethodUnitTests {
RepositoryMetadata metadata;
Method repositoryMethod, invalidReturnType, pageableAndSort, pageableTwice, sortableTwice, modifyingMethod,
nativeQuery;
nativeQuery, namedQuery;
/**
* @throws Exception
@@ -74,6 +74,7 @@ public class JpaQueryMethodUnitTests {
modifyingMethod = UserRepository.class.getMethod("renameAllUsersTo", String.class);
nativeQuery = InvalidRepository.class.getMethod("findByLastname", String.class);
namedQuery = InvalidRepository.class.getMethod("findByNamedQuery");
}
@Test
@@ -204,6 +205,15 @@ public class JpaQueryMethodUnitTests {
assertThat(method.isNativeQuery(), is(true));
}
/**
* @see DATAJPA-129
*/
@Test
public void considersAnnotatedNamedQueryName() {
JpaQueryMethod queryMethod = new JpaQueryMethod(namedQuery, metadata, extractor);
assertThat(queryMethod.getNamedQueryName(), is("Foo.bar"));
}
/**
* Interface to define invalid repository methods for testing.
*
@@ -237,5 +247,8 @@ public class JpaQueryMethodUnitTests {
@Query(value = "query", nativeQuery = true)
List<User> findByLastname(String lastname);
@Query(name = "Foo.bar")
List<User> findByNamedQuery();
}
}