DATAJPA-554 - Avoid falling back to query derivation for invalid native queries.

We now throw a dedicated InvalidJpaQueryMethodException with a more concrete exception message if we encounter a query method that is annotated with @Query(value = "…", native = true) and erroneously uses a Pageable or Sort parameter. Previously we only threw a IllegalStateException which was then recovered by the CreateIfNotFoundQueryLookupStrategy which tried to do query method derivation as a last resort. This resulted in a cryptic exception message to be thrown that indicates the derivation failure rather than the original error.

Original pull request: #97.
This commit is contained in:
Thomas Darimont
2014-06-17 12:17:28 +02:00
committed by Oliver Gierke
parent 8d320c966d
commit 94d63ac5d0
4 changed files with 77 additions and 6 deletions

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.jpa.repository.query;
/**
* Signals that we encountered an invalid query method.
*
* @author Thomas Darimont
* @author Oliver Gierke
*/
public class InvalidJpaQueryMethodException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates a new {@link InvalidJpaQueryMethodException} with the given message.
*
* @param message must not be {@literal null} or empty.
*/
public InvalidJpaQueryMethodException(String message) {
super(message);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013 the original author or authors.
* Copyright 2013-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,7 +45,8 @@ final class NativeJpaQuery extends AbstractStringBasedJpaQuery {
boolean hasPagingOrSortingParameter = parameters.hasPageableParameter() || parameters.hasSortParameter();
if (hasPagingOrSortingParameter) {
throw new IllegalStateException("Cannot use native queries with dynamic sorting and/or pagination!");
throw new InvalidJpaQueryMethodException(
"Cannot use native queries with dynamic sorting and/or pagination in method " + method);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2013 the original author or authors.
* Copyright 2012-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,10 +26,14 @@ import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.sample.User;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
@@ -43,6 +47,7 @@ import org.springframework.data.repository.query.QueryLookupStrategy.Key;
* Unit tests for {@link JpaQueryLookupStrategy}.
*
* @author Oliver Gierke
* @author Thomas Darimont
*/
@RunWith(MockitoJUnitRunner.class)
public class JpaQueryLookupStrategyUnitTests {
@@ -52,8 +57,11 @@ public class JpaQueryLookupStrategyUnitTests {
@Mock QueryExtractor extractor;
@Mock NamedQueries namedQueries;
public @Rule ExpectedException exception = ExpectedException.none();
@Before
public void setUp() {
when(em.getEntityManagerFactory()).thenReturn(emf);
when(emf.createEntityManager()).thenReturn(em);
}
@@ -79,9 +87,29 @@ public class JpaQueryLookupStrategyUnitTests {
}
}
/**
* @see DATAJPA-554
*/
@Test
public void sholdThrowMorePreciseExceptionIfTryingToUsePaginationInNativeQueries() throws Exception {
QueryLookupStrategy strategy = JpaQueryLookupStrategy.create(em, Key.CREATE_IF_NOT_FOUND, extractor);
Method method = UserRepository.class.getMethod("findByInvalidNativeQuery", String.class, Pageable.class);
RepositoryMetadata metadata = new DefaultRepositoryMetadata(UserRepository.class);
exception.expect(InvalidJpaQueryMethodException.class);
exception.expectMessage("Cannot use native queries with dynamic sorting and/or pagination in method");
exception.expectMessage(method.toString());
strategy.resolveQuery(method, metadata, namedQueries);
}
interface UserRepository extends Repository<User, Long> {
@Query("something absurd")
User findByFoo(String foo);
@Query(value = "select u.* from User u", nativeQuery = true)
Page<User> findByInvalidNativeQuery(String param, Pageable page);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2008-2013 the original author or authors.
* Copyright 2008-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -137,14 +137,20 @@ public class SimpleJpaQueryUnitTests {
verify(em).createNativeQuery("SELECT u FROM User u WHERE u.lastname = ?1", User.class);
}
@Test(expected = IllegalStateException.class)
/**
* @see DATAJPA-554
*/
@Test(expected = InvalidJpaQueryMethodException.class)
public void rejectsNativeQueryWithDynamicSort() throws Exception {
Method method = SampleRepository.class.getMethod("findNativeByLastname", String.class, Sort.class);
createJpaQuery(method);
}
@Test(expected = IllegalStateException.class)
/**
* @see DATAJPA-554
*/
@Test(expected = InvalidJpaQueryMethodException.class)
public void rejectsNativeQueryWithPageable() throws Exception {
Method method = SampleRepository.class.getMethod("findNativeByLastname", String.class, Pageable.class);