下面列出了org.springframework.context.expression.BeanFactoryAccessor#org.springframework.data.repository.query.Parameters 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
Map<String, Object> bindParameters(Neo4jParameterAccessor parameterAccessor) {
final Parameters<?, ?> formalParameters = parameterAccessor.getParameters();
Map<String, Object> resolvedParameters = new HashMap<>();
// Values from the parameter accessor can only get converted after evaluation
for (Map.Entry<String, Object> evaluatedParam : spelEvaluator.evaluate(parameterAccessor.getValues()).entrySet()) {
resolvedParameters.put(evaluatedParam.getKey(), super.convertParameter(evaluatedParam.getValue()));
}
formalParameters.stream()
.filter(Parameter::isBindable)
.forEach(parameter -> {
int parameterIndex = parameter.getIndex();
Object parameterValue = super.convertParameter(parameterAccessor.getBindableValue(parameterIndex));
// Add the parameter under its name when possible
parameter.getName()
.ifPresent(parameterName -> resolvedParameters.put(parameterName, parameterValue));
// Always add under its index.
resolvedParameters.put(Integer.toString(parameterIndex), parameterValue);
});
return resolvedParameters;
}
Map<String, Object> bindParameters(Neo4jParameterAccessor parameterAccessor) {
final Parameters<?, ?> formalParameters = parameterAccessor.getParameters();
Map<String, Object> resolvedParameters = new HashMap<>();
// Values from the parameter accessor can only get converted after evaluation
for (Map.Entry<String, Object> evaluatedParam : spelEvaluator.evaluate(parameterAccessor.getValues()).entrySet()) {
resolvedParameters.put(evaluatedParam.getKey(), super.convertParameter(evaluatedParam.getValue()));
}
formalParameters.stream()
.filter(Parameter::isBindable)
.forEach(parameter -> {
int parameterIndex = parameter.getIndex();
Object parameterValue = super.convertParameter(parameterAccessor.getBindableValue(parameterIndex));
// Add the parameter under its name when possible
parameter.getName()
.ifPresent(parameterName -> resolvedParameters.put(parameterName, parameterValue));
// Always add under its index.
resolvedParameters.put(Integer.toString(parameterIndex), parameterValue);
});
return resolvedParameters;
}
private void setOriginalParamTags() {
this.originalParamTags = new ArrayList<>();
Set<String> seen = new HashSet<>();
Parameters parameters = getQueryMethod().getParameters();
for (int i = 0; i < parameters.getNumberOfParameters(); i++) {
Parameter param = parameters.getParameter(i);
if (Pageable.class.isAssignableFrom(param.getType()) || Sort.class.isAssignableFrom(param.getType())) {
continue;
}
Optional<String> paramName = param.getName();
if (!paramName.isPresent()) {
throw new DatastoreDataException(
"Query method has a parameter without a valid name: "
+ getQueryMethod().getName());
}
String name = paramName.get();
if (seen.contains(name)) {
throw new DatastoreDataException(
"More than one param has the same name: " + name);
}
seen.add(name);
this.originalParamTags.add(name);
}
}
private QueryMethodEvaluationContextProvider delegateContextProvider(
QueryMethodEvaluationContextProvider evaluationContextProvider) {
return new QueryMethodEvaluationContextProvider() {
@Override
public <T extends Parameters<?, ?>> EvaluationContext getEvaluationContext(
T parameters, Object[] parameterValues) {
StandardEvaluationContext evaluationContext = (StandardEvaluationContext)
evaluationContextProvider
.getEvaluationContext(parameters, parameterValues);
evaluationContext.setRootObject(
DatastoreRepositoryFactory.this.applicationContext);
evaluationContext.addPropertyAccessor(new BeanFactoryAccessor());
evaluationContext.setBeanResolver(new BeanFactoryResolver(
DatastoreRepositoryFactory.this.applicationContext));
return evaluationContext;
}
};
}
private Parameters buildParameters(Object[] params, String[] paramNames) {
Parameters parameters = mock(Parameters.class);
Mockito.<Parameters>when(this.queryMethod.getParameters())
.thenReturn(parameters);
when(parameters.getNumberOfParameters()).thenReturn(paramNames.length);
when(parameters.getParameter(anyInt())).thenAnswer((invocation) -> {
int index = invocation.getArgument(0);
Parameter param = mock(Parameter.class);
when(param.getName())
.thenReturn(paramNames[index] == null ? Optional.empty() : Optional.of(paramNames[index]));
Mockito.<Class>when(param.getType()).thenReturn(params[index].getClass());
return param;
});
return parameters;
}
private List<String> getParamTags() {
List<String> tags = new ArrayList<>();
Set<String> seen = new HashSet<>();
Parameters<?, ?> parameters = getQueryMethod().getParameters();
for (int i = 0; i < parameters.getNumberOfParameters(); i++) {
Parameter param = parameters.getParameter(i);
if (isPageableOrSort(param.getType())) {
continue;
}
Optional<String> paramName = param.getName();
if (!paramName.isPresent()) {
throw new SpannerDataException(
"Query method has a parameter without a valid name: "
+ getQueryMethod().getName());
}
String name = paramName.get();
if (seen.contains(name)) {
throw new SpannerDataException(
"More than one param has the same name: " + name);
}
seen.add(name);
tags.add(name);
}
return tags;
}
private QueryMethodEvaluationContextProvider delegateContextProvider(
QueryMethodEvaluationContextProvider evaluationContextProvider) {
return new QueryMethodEvaluationContextProvider() {
@Override
public <T extends Parameters<?, ?>> EvaluationContext getEvaluationContext(
T parameters, Object[] parameterValues) {
StandardEvaluationContext evaluationContext = (StandardEvaluationContext) evaluationContextProvider
.getEvaluationContext(parameters, parameterValues);
evaluationContext
.setRootObject(SpannerRepositoryFactory.this.applicationContext);
evaluationContext.addPropertyAccessor(new BeanFactoryAccessor());
evaluationContext.setBeanResolver(new BeanFactoryResolver(
SpannerRepositoryFactory.this.applicationContext));
return evaluationContext;
}
};
}
/**
* Creates a new {@link NativeEbeanUpdate} encapsulating the query annotated on the given {@link EbeanQueryMethod}.
*
* @param method must not be {@literal null}.
* @param ebeanServer must not be {@literal null}.
* @param queryString must not be {@literal null} or empty.
* @param evaluationContextProvider
*/
public NativeEbeanUpdate(EbeanQueryMethod method, EbeanServer ebeanServer, String queryString,
QueryMethodEvaluationContextProvider evaluationContextProvider, SpelExpressionParser parser) {
super(method, ebeanServer, queryString, evaluationContextProvider, parser);
Parameters<?, ?> parameters = method.getParameters();
boolean hasPagingOrSortingParameter = parameters.hasPageableParameter() || parameters.hasSortParameter();
boolean containsPageableOrSortInQueryExpression = queryString.contains("#pageable")
|| queryString.contains("#sort");
if (hasPagingOrSortingParameter && !containsPageableOrSortInQueryExpression) {
throw new InvalidEbeanQueryMethodException(
"Cannot use native queries with dynamic sorting and/or pagination in method " + method);
}
}
/**
* Creates a new {@link QueryMethod} from the given parameters. Looks up the correct
* query to use for following invocations of the method given.
* @param method must not be {@literal null}.
* @param metadata must not be {@literal null}.
* @param factory must not be {@literal null}.
*/
public MybatisQueryMethod(Method method, RepositoryMetadata metadata,
ProjectionFactory factory) {
super(method, metadata, factory);
Assert.notNull(method, "Method must not be null!");
this.method = method;
Assert.isTrue(!(isModifyingQuery() && getParameters().hasSpecialParameter()),
String.format("Modifying method must not contain %s!", Parameters.TYPES));
this.metadata = metadata;
String namespace = getAnnotationValue("namespace", String.class);
String statementName = getAnnotationValue("statement", String.class);
this.namespace = StringUtils.hasText(namespace) ? namespace
: metadata.getRepositoryInterface().getName();
this.statementName = StringUtils.hasText(statementName) ? statementName
: (method.getName() + UUID.randomUUID().toString().replace("-", ""));
}
static String buildQuery(final String rawQuery, Parameters parameters,
Object... parameterValues) {
String replacedRawQuery = rawQuery;
for (Iterator<Parameter> iterator = parameters.iterator(); iterator
.hasNext();) {
Parameter eachParameter = iterator.next();
if (Pageable.class.isAssignableFrom(eachParameter.getType())
|| Sort.class.isAssignableFrom(eachParameter.getType())) {
continue;
}
replacedRawQuery = replaceOneParameterInQuery(replacedRawQuery,
eachParameter, parameterValues[eachParameter.getIndex()]);
}
return replacedRawQuery.trim();
}
@Test
public void buildQueryConditionsWithParameters_should_work_with_the_same_placeholder_values_as_fieldkeys()
throws Exception {
// @Query(select = {"item_id", "sampleAttribute"}, where =
// "sampleAttribute<=:sampleAttribute and item_id = :item_id")
final String expectedQuery = "select item_id, sampleAttribute from `testDB.sampleEntity` where sampleAttribute<='3' and item_id = '5'";
SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectWithEqualPlaceholders",
SampleEntity.class);
final String toProcessRawQuery = repositoryMethod.getAnnotatedQuery();
final Parameters parameters = getMockParameters(new String[]{":sampleAttribute", ":item_id"}, new Class[]{String.class, String.class});
String resultedQuery = QueryUtils.buildQuery(toProcessRawQuery, parameters, "3", "5");
assertThat(resultedQuery, is(expectedQuery));
}
@Test
public void buildQueryConditionsWithParameters_should_work_with_different_placeholder_values_as_fieldkeys()
throws Exception {
// @Query(select = {"item_id", "sampleAttribute"}, where = "sampleAttribute<=:attribute and item_id = :item")
final String expectedQuery = "select item_id, sampleAttribute from `testDB.sampleEntity` where sampleAttribute<='3' and item_id = '5'";
SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectWithDifferentPlaceholders",
SampleEntity.class);
final String toProcessRawQuery = repositoryMethod.getAnnotatedQuery();
final Parameters parameters = getMockParameters(new String[]{":attribute", ":item"}, new Class[]{String.class, String.class});
String resultedQuery = QueryUtils.buildQuery(toProcessRawQuery, parameters, "3", "5");
assertThat(resultedQuery, is(expectedQuery));
}
@Test
public void buildQueryConditionsWithParameters_should_work_with_primitive_type_parameter_values() throws Exception {
// @Query(select = {"item_id", "sampleAttribute"}, where = "sampleAttribute<=:attribute and item_id = :item")
final int age = 5;
final String convertedAge = SimpleDBAttributeConverter.encode(age);
final String expectedQuery = "select item_id, sampleAttribute from `testDB.sampleEntity` where sampleAttribute<='3' and item_id = '"
+ convertedAge + "'";
SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectWithDifferentPlaceholders",
SampleEntity.class);
final String toProcessRawQuery = repositoryMethod.getAnnotatedQuery();
final Parameters parameters = getMockParameters(new String[]{":attribute", ":item"}, new Class[]{String.class, int.class});
String resultedQuery = QueryUtils.buildQuery(toProcessRawQuery, parameters, "3", 5);
assertThat(resultedQuery, is(expectedQuery));
}
@Test
public void buildQueryConditionsWithParameters_should_construct_correct_query_with_converted_parameter_values() {
final String bind_query = "select * from customer_all WHERE age = :age and email = :email and balance = :balance";
final int age = 23;
final String email = "[email protected]";
final float balance = 12.1f;
final String convertedAge = SimpleDBAttributeConverter.encode(age);
final String convertedBalance = SimpleDBAttributeConverter.encode(balance);
String expectedQuery = "select * from customer_all WHERE age = '" + convertedAge + "' and email = '" + email
+ "' and balance = '" + convertedBalance + "'";
final Parameters parameters = getMockParameters(new String[]{":age", ":email", ":balance"}, new Class[]{int.class, String.class, float.class});
String resultedQuery = QueryUtils.buildQuery(bind_query, parameters, age, email,
balance);
assertThat(resultedQuery, is(expectedQuery));
}
@Test
public void bindIndexPositionParameters_should_construct_correct_query_from_annotated_query_clauses()
throws Exception {
final int age = 23;
final String email = "[email protected]";
final String convertedAge = SimpleDBAttributeConverter.encode(age);
final SimpleDbQueryMethod queryMethod = prepareQueryMethodToTest("selectOrderedParameters", SampleEntity.class);
final String toProcessParsedQuery = queryMethod.getAnnotatedQuery();
// @Query(select = {"item_id", "sampleAttribute"}, where = "sampleAttribute<=? and item_id = ? ")
final String expectedQuery = "select item_id, sampleAttribute from `testDB.sampleEntity` where `sampleAttribute`<='"
+ convertedAge + "' and item_id = '" + email + "'";
final Parameters parameters = getMockParameters(new String[]{"?","?"}, new Class[]{int.class, String.class, String.class});
final String resultedQuery = QueryUtils.buildQuery(toProcessParsedQuery, parameters, age, email);
assertThat(resultedQuery, is(expectedQuery));
}
@Test
public void bindIndexPositionParameters_should_construct_correct_query_with_converted_parameter_values() {
final int age = 23;
final String email = "[email protected]";
final float balance = 12.1f;
final String convertedAge = SimpleDBAttributeConverter.encode(age);
final String convertedBalance = SimpleDBAttributeConverter.encode(balance);
String expectedQuery = "select * from customer_all WHERE age = '" + convertedAge + "' and email = '" + email
+ "' and balance = '" + convertedBalance + "'";
final Parameters parameters = getMockParameters(new String[]{"?","?","?"}, new Class[]{int.class, String.class, float.class});
String resultedQuery = QueryUtils.buildQuery(BIND_QUERY, parameters, age, email, balance);
assertThat(resultedQuery, is(expectedQuery));
}
@Test
public void buildQueryConditionsWithParameters_should_construct_correct_bind_query_for_in_operator() {
final String bind_query = "select * from customer_all WHERE age in ?";
final long firstAge = 23;
final long secondAge = 25;
final String convertedFirstAge = SimpleDBAttributeConverter.encode(firstAge);
final String convertedSecondAge = SimpleDBAttributeConverter.encode(secondAge);
String expectedQuery = "select * from customer_all WHERE age in ('" + convertedFirstAge + "','"
+ convertedSecondAge + "')";
final Parameters parameters = getMockParameters(new String[] { "?" }, new Class[] { long[].class });
String resultedQuery = QueryUtils.buildQuery(bind_query, parameters, new long[] { firstAge, secondAge });
assertThat(resultedQuery, is(expectedQuery));
}
/**
* This test shows that if a named param or an index param is used to replace a field name, this will generate an
* invalid query because quotes are added surrounding the field name
*/
@Ignore
@Test
public void buildQueryConditionsWithParameters_should_construct_The_trickiest_query_for_in_operator() {
final String bind_query = "select * from customer_all WHERE ?=?";
final long firstAge = 23;
final String convertedFirstAge = SimpleDBAttributeConverter.encode(firstAge);
String expectedQuery = "select * from customer_all WHERE name = '" + convertedFirstAge + "'";
final Parameters parameters = getMockParameters("?", "?");
String resultedQuery = QueryUtils.buildQuery(bind_query, parameters, "name", firstAge);
assertThat(resultedQuery, is(expectedQuery));
}
@Test
public void buildQueryConditionsWithParameters_should_construct_correct_named_query_for_in_operator() {
final String bind_query = "select * from customer_all WHERE age in :age and x= :name";
final int firstAge = 23;
final int secondAge = 25;
final String convertedFirstAge = SimpleDBAttributeConverter.encode(firstAge);
final String convertedSecondAge = SimpleDBAttributeConverter.encode(secondAge);
String expectedQuery = "select * from customer_all WHERE age in ('" + convertedFirstAge + "','"+convertedSecondAge+"') and x= 'name'";
final Parameters parameters = getMockParameters(new String[]{":name", ":age"}, new Class[]{String.class, int[].class});
String resultedQuery = QueryUtils.buildQuery(bind_query, parameters, "name", new int[]{firstAge, secondAge});
assertThat(resultedQuery, is(expectedQuery));
}
@Test
public void buildQueryConditionsWithParameters_should_construct_correct_named_query_for_in_operator_with_no_space() {
final String bind_query = "select * from customer_all WHERE age in:age";
final int firstAge = 23;
final int secondAge = 25;
final String convertedFirstAge = SimpleDBAttributeConverter.encode(firstAge);
final String convertedSecondAge = SimpleDBAttributeConverter.encode(secondAge);
String expectedQuery = "select * from customer_all WHERE age in('" + convertedFirstAge + "','"+convertedSecondAge+"')";
final Parameters parameters = getMockParameters(new String[]{":age"}, new Class[]{String.class});
String resultedQuery = QueryUtils.buildQuery(bind_query, parameters, new int[]{firstAge, secondAge});
assertThat(resultedQuery, is(expectedQuery));
}
@Test
public void resolveSqlQueryTest() {
String queryName = "fakeNamedQueryName";
String query = "fake query";
when(this.queryMethod.getNamedQueryName()).thenReturn(queryName);
Query queryAnnotation = mock(Query.class);
when(this.queryMethod.getQueryAnnotation()).thenReturn(queryAnnotation);
NamedQueries namedQueries = mock(NamedQueries.class);
Parameters parameters = mock(Parameters.class);
Mockito.<Parameters>when(this.queryMethod.getParameters())
.thenReturn(parameters);
when(parameters.getNumberOfParameters()).thenReturn(1);
when(parameters.getParameter(anyInt())).thenAnswer((invocation) -> {
Parameter param = mock(Parameter.class);
when(param.getName()).thenReturn(Optional.of("tag"));
Mockito.<Class>when(param.getType()).thenReturn(Object.class);
return param;
});
when(namedQueries.hasQuery(eq(queryName))).thenReturn(true);
when(namedQueries.getQuery(eq(queryName))).thenReturn(query);
this.datastoreQueryLookupStrategy.resolveQuery(null, null, null, namedQueries);
verify(this.datastoreQueryLookupStrategy, times(1)).createGqlDatastoreQuery(
eq(Object.class), same(this.queryMethod), eq(query));
}
@Test
public void resolveSqlQueryTest() {
String queryName = "fakeNamedQueryName";
String query = "fake query";
when(this.queryMethod.getNamedQueryName()).thenReturn(queryName);
NamedQueries namedQueries = mock(NamedQueries.class);
Parameters parameters = mock(Parameters.class);
// @formatter:off
Mockito.<Parameters>when(this.queryMethod.getParameters()).thenReturn(parameters);
// @formatter:off
when(parameters.getNumberOfParameters()).thenReturn(1);
when(parameters.getParameter(anyInt())).thenAnswer((invocation) -> {
Parameter param = mock(Parameter.class);
when(param.getName()).thenReturn(Optional.of("tag"));
// @formatter:off
Mockito.<Class>when(param.getType()).thenReturn(Object.class);
// @formatter:on
return param;
});
when(namedQueries.hasQuery(eq(queryName))).thenReturn(true);
when(namedQueries.getQuery(eq(queryName))).thenReturn(query);
this.spannerQueryLookupStrategy.resolveQuery(null, null, null, namedQueries);
verify(this.spannerQueryLookupStrategy, times(1)).createSqlSpannerQuery(
eq(Object.class), same(this.queryMethod), eq(query), eq(false));
}
@Test
public void dmlTest() throws NoSuchMethodException {
String sql = "dml statement here";
TransactionContext context = mock(TransactionContext.class);
TransactionRunner transactionRunner = mock(TransactionRunner.class);
when(this.databaseClient.readWriteTransaction()).thenReturn(transactionRunner);
when(transactionRunner.run(any())).thenAnswer((invocation) -> {
TransactionRunner.TransactionCallable transactionCallable = invocation.getArgument(0);
return transactionCallable.run(context);
});
Method method = QueryHolder.class.getMethod("noParamMethod");
Mockito.<Parameters>when(this.queryMethod.getParameters())
.thenReturn(new DefaultParameters(method));
SqlSpannerQuery sqlSpannerQuery = spy(createQuery(sql, Trade.class, true));
doReturn(long.class).when(sqlSpannerQuery)
.getReturnedSimpleConvertableItemType();
doReturn(null).when(sqlSpannerQuery).convertToSimpleReturnType(any(),
any());
sqlSpannerQuery.execute(new Object[] {});
verify(this.spannerTemplate, times(1)).executeDmlStatement(any());
}
private PartTreeFirestoreQuery setUpPartTreeFirestoreQuery(String methodName) {
Parameters parametersMock = mock(Parameters.class);
when(parametersMock.isEmpty()).thenReturn(true);
when(this.queryMethod.getParameters()).thenReturn(parametersMock);
when(this.queryMethod.getName()).thenReturn(methodName);
ReturnedType returnedType = mock(ReturnedType.class);
when(returnedType.getDomainType()).thenAnswer(invocation -> User.class);
ResultProcessor resultProcessor = mock(ResultProcessor.class);
when(resultProcessor.getReturnedType()).thenReturn(returnedType);
when(this.queryMethod.getResultProcessor()).thenReturn(resultProcessor);
return new PartTreeFirestoreQuery(this.queryMethod,
this.firestoreTemplate, new FirestoreMappingContext(), this.classMapper);
}
/**
* Creates a new {@link ParameterMetadataProvider} from the given {@link Iterable} of all
* bindable parameter values.
*
* @param bindableParameterValues may be {@literal null}.
* @param parameters must not be {@literal null}.
*/
private ParameterMetadataProvider(Iterator<Object> bindableParameterValues,
Parameters<?, ?> parameters) {
Assert.notNull(parameters, "Parameters must not be null!");
this.parameters = parameters.getBindableParameters().iterator();
this.expressions = new ArrayList<ParameterMetadata<?>>();
this.bindableParameterValues = bindableParameterValues;
}
TemplateBasedQueryParameterSetterFactory(ExpressionParser parser,
EvaluationContextProvider evaluationContextProvider, Parameters<?, ?> parameters) {
Assert.notNull(evaluationContextProvider, "EvaluationContextProvider must not be null!");
Assert.notNull(parser, "ExpressionParser must not be null!");
Assert.notNull(parameters, "Parameters must not be null!");
this.evaluationContextProvider = evaluationContextProvider;
this.parser = parser;
this.parameters = parameters;
}
/**
* @param evaluationCtxProvider Evaluation context provider.
* @param parameters Parameters.
* @param extractor Extractor.
*/
public SpelEvaluator(EvaluationContextProvider evaluationCtxProvider,
Parameters<?, ?> parameters,
SpelExtractor extractor) {
this.evaluationCtxProvider = evaluationCtxProvider;
this.parameters = parameters;
this.extractor = extractor;
}
/**
* <p>
* Determine if the arguments to the method need reordered.
* </P>
* <p>
* For searches such as {@code findBySomethingNotNull} there may be more parts than parameters needed to be bound to
* them.
* </P>
*
* @param partTree Query parts
* @param bindableParameters Parameters expected
*/
@SuppressWarnings("unchecked")
private void prepareRearrange(final PartTree partTree, final Parameters<?, ?> bindableParameters) {
this.isRearrangeRequired = false;
if (partTree == null || bindableParameters == null) {
return;
}
List<String> queryParams = new ArrayList<>();
List<String> methodParams = new ArrayList<>();
for (Part part : partTree.getParts()) {
queryParams.add(part.getProperty().getSegment());
}
Iterator<Parameter> bindableParameterIterator = (Iterator<Parameter>) bindableParameters.iterator();
while (bindableParameterIterator.hasNext()) {
Parameter parameter = bindableParameterIterator.next();
parameter.getName().ifPresent(methodParams::add);
}
this.rearrangeIndex = new int[queryParams.size()];
String[] paramsExpected = queryParams.toArray(new String[0]);
String[] paramsProvided = methodParams.toArray(new String[0]);
for (int i = 0; i < this.rearrangeIndex.length; i++) {
this.rearrangeIndex[i] = i;
for (int j = 0; j < paramsProvided.length; j++) {
if (paramsProvided[j] != null && paramsProvided[j].equals(paramsExpected[i])) {
this.rearrangeIndex[i] = j;
this.isRearrangeRequired = true;
}
}
}
}
/**
* Creates a new {@link SimpleJpaQuery} that encapsulates a simple query string.
*/
SimpleJpaQuery(JpaQueryMethod method, EntityManager em, String queryString) {
super(method, em);
this.method = method;
this.query = new StringQuery(queryString);
this.countQuery = new StringQuery(method.getCountQuery() == null ? QueryUtils.createCountQueryFor(queryString)
: method.getCountQuery());
Parameters parameters = method.getParameters();
boolean hasPagingOrSortingParameter = parameters.hasPageableParameter() || parameters.hasSortParameter();
if (method.isNativeQuery() && hasPagingOrSortingParameter) {
throw new IllegalStateException("Cannot use native queries with dynamic sorting and/or pagination!");
}
EntityManager target = null;
// Try to create a Query object already to fail fast
if (!method.isNativeQuery()) {
try {
target = em.getEntityManagerFactory().createEntityManager();
target.createQuery(query.getQuery());
} catch (RuntimeException e) {
// Needed as there's ambiguities in how an invalid query string shall be expressed by the persistence provider
// http://java.net/projects/jpa-spec/lists/jsr338-experts/archive/2012-07/message/17
throw e instanceof IllegalArgumentException ? e : new IllegalArgumentException(e);
} finally {
EntityManagerFactoryUtils.closeEntityManager(target);
}
}
}
public static String bindQueryParameters(SimpleDbQueryMethod queryMethod,
Object... parameterValues) {
final String rawQuery = queryMethod.getAnnotatedQuery();
if (hasNamedParameter(queryMethod) || hasBindParameter(rawQuery)) {
final Parameters parameters = queryMethod.getParameters();
return buildQuery(rawQuery, parameters, parameterValues);
}
return rawQuery;
}