Skip to content

Commit

Permalink
DATAJPA-758 - Named parameters for derived are only used if they're e…
Browse files Browse the repository at this point in the history
…xplicitly named.

If parameter names for derived queries use names that collide with reserved keywords in JPQL (e.g. key) switching on Java 8 parameter name discovery previously caused the query execution to fail.

We now check whether the parameter has been explicitly named (using the @param annotation) and only use the name if so.
  • Loading branch information
odrotbohm committed Jul 15, 2015
1 parent 0a89b92 commit 8de3100
Show file tree
Hide file tree
Showing 6 changed files with 176 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.springframework.core.MethodParameter;
import org.springframework.data.jpa.repository.Temporal;
import org.springframework.data.jpa.repository.query.JpaParameters.JpaParameter;
import org.springframework.data.repository.query.Param;
import org.springframework.data.repository.query.Parameter;
import org.springframework.data.repository.query.Parameters;

Expand Down Expand Up @@ -74,6 +75,7 @@ protected JpaParameters createFrom(List<JpaParameter> parameters) {
static class JpaParameter extends Parameter {

private final Temporal annotation;
private final boolean explicitlyNamed;
private TemporalType temporalType;

/**
Expand All @@ -86,11 +88,12 @@ static class JpaParameter extends Parameter {
super(parameter);

this.annotation = parameter.getParameterAnnotation(Temporal.class);
this.explicitlyNamed = parameter.getParameterAnnotation(Param.class) != null;
this.temporalType = null;

if (!isDateParameter() && hasTemporalParamAnnotation()) {
throw new IllegalArgumentException(Temporal.class.getSimpleName()
+ " annotation is only allowed on Date parameter!");
throw new IllegalArgumentException(
Temporal.class.getSimpleName() + " annotation is only allowed on Date parameter!");
}
}

Expand Down Expand Up @@ -122,6 +125,10 @@ public TemporalType getTemporalType() {
return this.temporalType;
}

public boolean isExplicitlyNamed() {
return explicitlyNamed;
}

private boolean hasTemporalParamAnnotation() {
return annotation != null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import javax.persistence.criteria.ParameterExpression;

import org.springframework.data.jpa.provider.PersistenceProvider;
import org.springframework.data.jpa.repository.query.JpaParameters.JpaParameter;
import org.springframework.data.repository.query.Parameter;
import org.springframework.data.repository.query.Parameters;
import org.springframework.data.repository.query.ParametersParameterAccessor;
Expand All @@ -45,7 +46,7 @@
class ParameterMetadataProvider {

private final CriteriaBuilder builder;
private final Iterator<? extends Parameter> parameters;
private final Iterator<? extends JpaParameter> parameters;
private final List<ParameterMetadata<?>> expressions;
private final Iterator<Object> bindableParameterValues;
private final PersistenceProvider persistenceProvider;
Expand All @@ -61,8 +62,7 @@ class ParameterMetadataProvider {
*/
public ParameterMetadataProvider(CriteriaBuilder builder, ParametersParameterAccessor accessor,
PersistenceProvider provider) {

this(builder, accessor.iterator(), accessor.getParameters(), provider);
this(builder, accessor.iterator(), (JpaParameters) accessor.getParameters(), provider);
}

/**
Expand All @@ -73,7 +73,7 @@ public ParameterMetadataProvider(CriteriaBuilder builder, ParametersParameterAcc
* @param parameters must not be {@literal null}.
* @param provider must not be {@literal null}.
*/
public ParameterMetadataProvider(CriteriaBuilder builder, Parameters<?, ?> parameters, PersistenceProvider provider) {
public ParameterMetadataProvider(CriteriaBuilder builder, JpaParameters parameters, PersistenceProvider provider) {

this(builder, null, parameters, provider);
}
Expand All @@ -89,7 +89,7 @@ public ParameterMetadataProvider(CriteriaBuilder builder, Parameters<?, ?> param
* @param provider must not be {@literal null}.
*/
private ParameterMetadataProvider(CriteriaBuilder builder, Iterator<Object> bindableParameterValues,
Parameters<?, ?> parameters, PersistenceProvider provider) {
JpaParameters parameters, PersistenceProvider provider) {

Assert.notNull(builder);
Assert.notNull(parameters);
Expand Down Expand Up @@ -120,8 +120,8 @@ public List<ParameterMetadata<?>> getExpressions() {
@SuppressWarnings("unchecked")
public <T> ParameterMetadata<T> next(Part part) {

Parameter parameter = parameters.next();
return (ParameterMetadata<T>) next(part, parameter.getType(), parameter.getName());
JpaParameter parameter = parameters.next();
return (ParameterMetadata<T>) next(part, parameter.getType(), parameter);
}

/**
Expand All @@ -135,9 +135,9 @@ public <T> ParameterMetadata<T> next(Part part) {
@SuppressWarnings("unchecked")
public <T> ParameterMetadata<? extends T> next(Part part, Class<T> type) {

Parameter parameter = parameters.next();
JpaParameter parameter = parameters.next();
Class<?> typeToUse = ClassUtils.isAssignable(type, parameter.getType()) ? parameter.getType() : type;
return (ParameterMetadata<? extends T>) next(part, typeToUse, null);
return (ParameterMetadata<? extends T>) next(part, typeToUse, parameter);
}

/**
Expand All @@ -149,7 +149,7 @@ public <T> ParameterMetadata<? extends T> next(Part part, Class<T> type) {
* @param name
* @return
*/
private <T> ParameterMetadata<T> next(Part part, Class<T> type, String name) {
private <T> ParameterMetadata<T> next(Part part, Class<T> type, JpaParameter parameter) {

Assert.notNull(type);

Expand All @@ -159,8 +159,8 @@ private <T> ParameterMetadata<T> next(Part part, Class<T> type, String name) {
@SuppressWarnings("unchecked")
Class<T> reifiedType = Expression.class.equals(type) ? (Class<T>) Object.class : type;

ParameterExpression<T> expression = name == null ? builder.parameter(reifiedType) : builder.parameter(reifiedType,
name);
ParameterExpression<T> expression = parameter.isExplicitlyNamed()
? builder.parameter(reifiedType, parameter.getName()) : builder.parameter(reifiedType);
ParameterMetadata<T> value = new ParameterMetadata<T>(expression, part.getType(),
bindableParameterValues == null ? ParameterMetadata.PLACEHOLDER : bindableParameterValues.next(),
this.persistenceProvider);
Expand Down Expand Up @@ -233,8 +233,8 @@ public Object prepare(Object value) {
case CONTAINING:
return String.format("%%%s%%", value.toString());
default:
return Collection.class.isAssignableFrom(expression.getJavaType()) ? persistenceProvider
.potentiallyConvertEmptyCollection(toCollection(value)) : value;
return Collection.class.isAssignableFrom(expression.getJavaType())
? persistenceProvider.potentiallyConvertEmptyCollection(toCollection(value)) : value;
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright 2015 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;

import org.springframework.test.context.ContextConfiguration;

/**
* EclipseLink-specific tests for {@link ParameterMetadataProvider}.
*
* @author Oliver Gierke
* @soundtrack Elephants Crossing - We are (Irrelephant)
*/
@ContextConfiguration("classpath:eclipselink.xml")
public class EclipseLinkParameterMetadataProviderIntegrationTests extends ParameterMetadataProviderIntegrationTests {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright 2015 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;

import org.springframework.test.context.ContextConfiguration;

/**
* OpenJpa-specific tests for {@link ParameterMetadataProvider}.
*
* @author Oliver Gierke
* @soundtrack Elephants Crossing - We are (Irrelephant)
*/
@ContextConfiguration("classpath:openjpa.xml")
public class OpenJpaParameterMetadataProviderIntegrationTests extends ParameterMetadataProviderIntegrationTests {}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import org.junit.runner.RunWith;
import org.springframework.data.jpa.domain.sample.User;
import org.springframework.data.jpa.provider.PersistenceProvider;
import org.springframework.data.repository.query.DefaultParameters;
import org.springframework.data.repository.query.Parameters;
import org.springframework.data.repository.query.ParametersParameterAccessor;
import org.springframework.data.repository.query.parser.Part;
Expand All @@ -40,7 +39,7 @@ public class ParameterExpressionProviderTests {
public void createsParameterExpressionWithMostConcreteType() throws Exception {

Method method = SampleRepository.class.getMethod("findByIdGreaterThan", int.class);
Parameters<?, ?> parameters = new DefaultParameters(method);
Parameters<?, ?> parameters = new JpaParameters(method);
ParametersParameterAccessor accessor = new ParametersParameterAccessor(parameters, new Object[] { 1 });
Part part = new Part("IdGreaterThan", User.class);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* Copyright 2015 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;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import java.lang.reflect.Method;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.jpa.domain.sample.User;
import org.springframework.data.jpa.provider.PersistenceProvider;
import org.springframework.data.jpa.repository.query.ParameterMetadataProvider.ParameterMetadata;
import org.springframework.data.repository.query.Param;
import org.springframework.data.repository.query.Parameters;
import org.springframework.data.repository.query.parser.Part;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.util.ReflectionTestUtils;

/**
* Integration tests for {@link ParameterMetadataProvider}.
*
* @author Oliver Gierke
* @soundtrack Elephants Crossing - We are (Irrelephant)
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:infrastructure.xml")
public class ParameterMetadataProviderIntegrationTests {

@PersistenceContext EntityManager em;

/**
* @see DATAJPA-758
*/
@Test
public void forwardsParameterNameIfTransparentlyNamed() throws Exception {

ParameterMetadataProvider provider = createProvider(Sample.class.getMethod("findByFirstname", String.class));
ParameterMetadata<Object> metadata = provider.next(new Part("firstname", User.class));

assertThat(metadata.getExpression().getName(), is("name"));
}

/**
* @see DATAJPA-758
*/
@Test
public void forwardsParameterNameIfExplicitlyAnnotated() throws Exception {

ParameterMetadataProvider provider = createProvider(Sample.class.getMethod("findByLastname", String.class));
ParameterMetadata<Object> metadata = provider.next(new Part("lastname", User.class));

assertThat(metadata.getExpression().getName(), is(nullValue()));
}

private ParameterMetadataProvider createProvider(Method method) {

JpaParameters parameters = new JpaParameters(method);
simulateDiscoveredParametername(parameters, 0, "name");

return new ParameterMetadataProvider(em.getCriteriaBuilder(), parameters,
PersistenceProvider.fromEntityManager(em));
}

@SuppressWarnings("unchecked")
private static void simulateDiscoveredParametername(Parameters<?, ?> parameters, int index, String name) {

List<Object> list = (List<Object>) ReflectionTestUtils.getField(parameters, "parameters");
Object parameter = ReflectionTestUtils.getField(list.get(0), "parameter");
ReflectionTestUtils.setField(parameter, "parameterName", name);
}

interface Sample {

User findByFirstname(@Param("name") String firstname);

User findByLastname(String lastname);
}
}

0 comments on commit 8de3100

Please sign in to comment.