org.springframework.data.repository.query.Parameters Java Examples
The following examples show how to use
org.springframework.data.repository.query.Parameters.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: QueryUtilsNamedQueryTest.java From spring-data-simpledb with MIT License | 6 votes |
@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)); }
Example #2
Source File: StringBasedNeo4jQuery.java From sdn-rx with Apache License 2.0 | 6 votes |
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; }
Example #3
Source File: QueryUtilsIndexByQueryTest.java From spring-data-simpledb with MIT License | 6 votes |
/** * 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)); }
Example #4
Source File: QueryUtilsArrayTest.java From spring-data-simpledb with MIT License | 6 votes |
@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)); }
Example #5
Source File: GqlDatastoreQuery.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
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); } }
Example #6
Source File: QueryUtilsArrayTest.java From spring-data-simpledb with MIT License | 6 votes |
@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)); }
Example #7
Source File: GqlDatastoreQueryTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
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; }
Example #8
Source File: DatastoreRepositoryFactory.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
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; } }; }
Example #9
Source File: ReactiveStringBasedNeo4jQuery.java From sdn-rx with Apache License 2.0 | 6 votes |
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; }
Example #10
Source File: SqlSpannerQuery.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
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; }
Example #11
Source File: QueryUtilsIndexByQueryTest.java From spring-data-simpledb with MIT License | 6 votes |
@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)); }
Example #12
Source File: NativeEbeanUpdate.java From spring-data-ebean with Apache License 2.0 | 6 votes |
/** * 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); } }
Example #13
Source File: SimpleDbIndexByQueryMethodBindedTest.java From spring-data-simpledb with MIT License | 6 votes |
@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)); }
Example #14
Source File: MybatisQueryMethod.java From spring-data-mybatis with Apache License 2.0 | 6 votes |
/** * 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("-", "")); }
Example #15
Source File: QueryUtils.java From spring-data-simpledb with MIT License | 6 votes |
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(); }
Example #16
Source File: SimpleDbNamedQueryMethodBindedTest.java From spring-data-simpledb with MIT License | 6 votes |
@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)); }
Example #17
Source File: SimpleDbNamedQueryMethodBindedTest.java From spring-data-simpledb with MIT License | 6 votes |
@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)); }
Example #18
Source File: SpannerRepositoryFactory.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
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; } }; }
Example #19
Source File: SimpleDbNamedQueryMethodBindedTest.java From spring-data-simpledb with MIT License | 6 votes |
@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)); }
Example #20
Source File: QueryUtilsIndexByQueryTest.java From spring-data-simpledb with MIT License | 6 votes |
@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)); }
Example #21
Source File: QueryUtilsNamedQueryTest.java From spring-data-simpledb with MIT License | 5 votes |
@Test public void buildQueryConditionsWithParameters_should_work_with_WHERE_clause() { final String expectedQuery = "select * from spring_data where type = 'spring-type'"; final String rawQuery = "select * from spring_data where type = :type"; final Parameters parameters = getMockParameters(new String[]{":type"}, new Class[]{String.class}); String resultedQuery = QueryUtils.buildQuery(rawQuery, parameters, "spring-type"); assertThat(resultedQuery, is(expectedQuery)); }
Example #22
Source File: SimpleDbQueryMethod.java From spring-data-simpledb with MIT License | 5 votes |
/** * Creates a new {@link org.springframework.data.simpledb.query.SimpleDbQueryMethod} * * @param method * must not be {@literal null} * @param metadata * must not be {@literal null} * @param simpleDbDomain */ public SimpleDbQueryMethod(Method method, RepositoryMetadata metadata, SimpleDbDomain simpleDbDomain) { super(method, metadata); this.method = method; this.simpleDbDomain = simpleDbDomain; Assert.isTrue(!(isModifyingQuery() && getParameters().hasSpecialParameter()), String.format("Modifying method must not contain %s!", Parameters.TYPES)); }
Example #23
Source File: SimpleDbNamedQueryMethodBindedTest.java From spring-data-simpledb with MIT License | 5 votes |
@SuppressWarnings({ "rawtypes" }) private Parameters getMockParameters(String[] placeHolders, Class[] clazzes) { Parameters mockParameters = Mockito.mock(Parameters.class); List<Parameter> parameters = new ArrayList<Parameter>(placeHolders.length); for(int idx = 0; idx < placeHolders.length; ++idx) { parameters.add(getMockParameter(placeHolders[idx], idx, clazzes[idx])); } Mockito.when(mockParameters.iterator()).thenReturn(parameters.iterator()); Mockito.when(mockParameters.getNumberOfParameters()).thenReturn(parameters.size()); return mockParameters; }
Example #24
Source File: QueryUtilsNamedQueryTest.java From spring-data-simpledb with MIT License | 5 votes |
@Ignore @Test public void buildQueryConditionsWithParameters_should_work_with_complex_parameters() { final String expectedQuery = "select * from spring_data where name = 'spring-name' and type = 'spring-type'"; final String rawQuery = "select * from spring_data where name = ::name and type = :"; final Parameters parameters = getMockParameters(new String[]{"::name", ":"}, new Class[]{String.class, String.class}); String resultedQuery = QueryUtils.buildQuery(rawQuery, parameters, "spring-name", "spring-type"); assertThat(resultedQuery, is(expectedQuery)); }
Example #25
Source File: QueryUtilsNamedQueryTest.java From spring-data-simpledb with MIT License | 5 votes |
@Test public void like_operators_should_be_wrapped_in_quotes() { final String expectedQuery = "select * from spring_data where first_name like '%joe' and last_name like 'dev%' and middle_name like '%o%'"; final String rawQuery = "select * from spring_data where first_name like %:fname and last_name like :lname% and middle_name like %:mname%"; final Parameters parameters = getMockParameters(new String[]{":fname", ":lname", ":mname"}, new Class[]{String.class, String.class, String.class}); String resultedQuery = QueryUtils.buildQuery(rawQuery, parameters, "joe", "dev", "o"); assertThat(resultedQuery, is(expectedQuery)); }
Example #26
Source File: HazelcastPartTreeQuery.java From spring-data-hazelcast with Apache License 2.0 | 5 votes |
/** * <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; } } } }
Example #27
Source File: SpelEvaluator.java From ignite with Apache License 2.0 | 5 votes |
/** * @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; }
Example #28
Source File: QueryUtilsNamedQueryTest.java From spring-data-simpledb with MIT License | 5 votes |
@Test public void buildQueryConditionsWithParameters_should_return_a_formatted_query() { final String expectedQuery = "select * from spring_data where name = 'spring-name' and type = 'spring-type' or location = 'Timisoara'"; final String rawQuery = "select * from spring_data where name = :name and type = :type or location = :location "; final Parameters parameters = getMockParameters(new String[]{":name", ":type", ":location"}, new Class[]{String.class, String.class, String.class}); String resultedQuery = QueryUtils.buildQuery(rawQuery, parameters, "spring-name", "spring-type", "Timisoara"); assertThat(resultedQuery, is(expectedQuery)); }
Example #29
Source File: QueryUtilsNamedQueryTest.java From spring-data-simpledb with MIT License | 5 votes |
@SuppressWarnings({ "rawtypes" }) private Parameters getMockParameters(String[] placeHolders, Class[] clazzes) { Parameters mockParameters = Mockito.mock(Parameters.class); List<Parameter> parameters = new ArrayList<Parameter>(placeHolders.length); for(int idx = 0; idx < placeHolders.length; ++idx) { parameters.add(getMockParameter(placeHolders[idx], idx, clazzes[idx])); } Mockito.when(mockParameters.iterator()).thenReturn(parameters.iterator()); Mockito.when(mockParameters.getNumberOfParameters()).thenReturn(parameters.size()); return mockParameters; }
Example #30
Source File: SimpleJpaQuery.java From es with Apache License 2.0 | 5 votes |
/** * 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); } } }