Skip to content

Adds support for parameterized @Query including ValueExpressions #505

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-ldap</artifactId>
<version>3.4.0-SNAPSHOT</version>
<version>3.4.0-GH-453-SNAPSHOT</version>

<name>Spring Data LDAP</name>
<description>Spring Data integration for LDAP</description>
Expand All @@ -21,6 +21,7 @@
<spring-ldap>3.2.6</spring-ldap>
<springdata.commons>3.4.0-SNAPSHOT</springdata.commons>
<java-module-name>spring.data.ldap</java-module-name>
<unboundid-ldapsdk>7.0.1</unboundid-ldapsdk>
</properties>

<developers>
Expand Down Expand Up @@ -109,6 +110,20 @@
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-test</artifactId>
<version>${spring-ldap}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>com.unboundid</groupId>
<artifactId>unboundid-ldapsdk</artifactId>
<version>${unboundid-ldapsdk}</version>
<scope>test</scope>
</dependency>

</dependencies>

<build>
Expand Down
2 changes: 2 additions & 0 deletions src/main/antora/modules/ROOT/nav.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@
** xref:repositories/namespace-reference.adoc[]
** xref:repositories/query-keywords-reference.adoc[]
** xref:repositories/query-return-types-reference.adoc[]

* xref:ldap.adoc[]
** xref:ldap/configuration.adoc[]
** xref:ldap/usage.adoc[]
** xref:ldap/query-methods.adoc[]
** xref:ldap/value-expressions.adoc[]
** xref:ldap/querydsl.adoc[]
** xref:ldap/cdi-integration.adoc[]

Expand Down
88 changes: 88 additions & 0 deletions src/main/antora/modules/ROOT/pages/ldap/query-methods.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,91 @@ The following table provides samples of the keywords that you can use with query
| `(!(Firstname=name))`

|===

[[ldap.query-methods.at-query]]
== Using `@Query`

If you need to use a custom query that can't be derived from the method name, you can use the `@Query` annotation to define the query.
As queries are tied to the Java method that runs them, you can actually bind parameters to be passed to the query.

The following example shows a query created with the `@Query` annotation:

.Declare query at the query method using `@Query`
====
[source,java]
----
interface PersonRepository extends LdapRepository<Person, Long> {

@Query("(&(employmentType=*)(!(employmentType=Hired))(mail=:emailAddress))")
Person findEmployeeByEmailAddress(String emailAddress);

}
----
====

NOTE: Spring Data supports named (parameter names prefixed with `:`) and positional parameter binding (in the form of zero-based `?0`).
We recommend using named parameters for easier readability.
Also, using positional parameters makes query methods a little error-prone when refactoring regarding the parameter position.

[[ldap.encoding]]
== Parameter Encoding

Query parameters of String-based queries are encoded according to https://datatracker.ietf.org/doc/html/rfc2254[RFC2254].
This can lead to undesired escaping of certain characters.
You can specify your own encoder through the `@LdapEncode` annotation that defines which javadoc:org.springframework.data.ldap.repository.LdapEncoder[] to use.

`@LdapEncode` applies to individual parameters of a query method.
It is not applies for derived queries or Value Expressions (SpEL, Property Placeholders).

.Declare a custom `LdapEncoder` for a query method
====
[source,java]
----
interface PersonRepository extends LdapRepository<Person, Long> {

@Query("(&(employmentType=*)(!(employmentType=Hired))(firstName=:firstName))")
Person findEmployeeByFirstNameLike(@LdapEncode(MyLikeEncoder.class) String firstName);

}
----
====

[[ldap.query.spel-expressions]]
== Using SpEL Expressions

Spring Data allows you to use SpEL expressions in your query methods.
SpEL expressions are part of Spring Data's xref:ldap/value-expressions.adoc[Value Expressions] support.
SpEL expressions can be used to manipulate query method arguments as well as to invoke bean methods.
Method arguments can be accessed by name or index as demonstrated in the following example.

.Using SpEL expressions in Repository Query Methods
====
[source,java]
----
@Query("(&(firstName=?#{[0]})(mail=:?#{principal.emailAddress}))")
List<Person> findByFirstnameAndCurrentUserWithCustomQuery(String firstname);
----
====

NOTE: Values provided by SpEL expressions are not escaped according to RFC2254.
You have to ensure that the values are properly escaped if needed.
Consider using Spring Ldap's `org.springframework.ldap.support.LdapEncoder` helper class.

[[ldap.query.property-placeholders]]
== Using Property Placeholders

Property Placeholders (see xref:ldap/value-expressions.adoc[Value Expressions]) can help to easily customize your queries based on configuration properties from Spring's `Environment`.
These are useful for queries that need to be customized based on the environment or configuration.

.Using Property Placeholders in Repository Query Methods
====
[source,java]
----
@Query("(&(firstName=?0)(stage=:?${myapp.stage:dev}))")
List<Person> findByFirstnameAndStageWithCustomQuery(String firstname);
----
====

NOTE: Values provided by Property Placeholders are not escaped according to RFC2254.
You have to ensure that the values are properly escaped if needed.
Consider using Spring Ldap's `org.springframework.ldap.support.LdapEncoder` helper class.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
include::{commons}@data-commons::page$value-expressions.adoc[]
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@

import static org.springframework.ldap.query.LdapQueryBuilder.*;

import org.springframework.data.expression.ValueEvaluationContext;
import org.springframework.data.expression.ValueEvaluationContextProvider;
import org.springframework.data.ldap.repository.Query;
import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mapping.model.EntityInstantiators;
import org.springframework.data.repository.query.ValueExpressionDelegate;
import org.springframework.ldap.core.LdapOperations;
import org.springframework.ldap.query.LdapQuery;
import org.springframework.util.Assert;
Expand All @@ -31,10 +34,14 @@
*
* @author Mattias Hellborg Arthursson
* @author Mark Paluch
* @author Marcin Grzejszczak
*/
public class AnnotatedLdapRepositoryQuery extends AbstractLdapRepositoryQuery {

private final Query queryAnnotation;
private final StringBasedQuery query;
private final StringBasedQuery base;
private final ValueEvaluationContextProvider valueContextProvider;

/**
* Construct a new instance.
Expand All @@ -44,26 +51,62 @@ public class AnnotatedLdapRepositoryQuery extends AbstractLdapRepositoryQuery {
* @param ldapOperations the LdapOperations instance to use.
* @param mappingContext must not be {@literal null}.
* @param instantiators must not be {@literal null}.
* @deprecated use the constructor with {@link ValueExpressionDelegate}
*/
@Deprecated(since = "3.4")
public AnnotatedLdapRepositoryQuery(LdapQueryMethod queryMethod, Class<?> entityType, LdapOperations ldapOperations,
MappingContext<? extends PersistentEntity<?, ?>, ? extends PersistentProperty<?>> mappingContext,
EntityInstantiators instantiators) {

this(queryMethod, entityType, ldapOperations, mappingContext, instantiators, ValueExpressionDelegate.create());
}

/**
* Construct a new instance.
*
* @param queryMethod the QueryMethod.
* @param entityType the managed class.
* @param ldapOperations the LdapOperations instance to use.
* @param mappingContext must not be {@literal null}.
* @param instantiators must not be {@literal null}.
* @param valueExpressionDelegate must not be {@literal null}
* @since 3.4
*/
public AnnotatedLdapRepositoryQuery(LdapQueryMethod queryMethod, Class<?> entityType, LdapOperations ldapOperations,
MappingContext<? extends PersistentEntity<?, ?>, ? extends PersistentProperty<?>> mappingContext,
EntityInstantiators instantiators, ValueExpressionDelegate valueExpressionDelegate) {

super(queryMethod, entityType, ldapOperations, mappingContext, instantiators);

Assert.notNull(queryMethod.getQueryAnnotation(), "Annotation must be present");
Assert.hasLength(queryMethod.getQueryAnnotation().value(), "Query filter must be specified");

queryAnnotation = queryMethod.getRequiredQueryAnnotation();
this.queryAnnotation = queryMethod.getRequiredQueryAnnotation();
this.query = new StringBasedQuery(queryAnnotation.value(), queryMethod.getParameters(), valueExpressionDelegate);
this.base = new StringBasedQuery(queryAnnotation.base(), queryMethod.getParameters(), valueExpressionDelegate);
this.valueContextProvider = valueExpressionDelegate.createValueContextProvider(getQueryMethod().getParameters());
}

@Override
protected LdapQuery createQuery(LdapParameterAccessor parameters) {

return query().base(queryAnnotation.base()) //
String query = bind(parameters, valueContextProvider, this.query);
String base = bind(parameters, valueContextProvider, this.base);

return query().base(base) //
.searchScope(queryAnnotation.searchScope()) //
.countLimit(queryAnnotation.countLimit()) //
.timeLimit(queryAnnotation.timeLimit()) //
.filter(queryAnnotation.value(), parameters.getBindableParameterValues());
.filter(query, parameters.getBindableParameterValues());
}

private String bind(LdapParameterAccessor parameters, ValueEvaluationContextProvider valueContextProvider, StringBasedQuery query) {

ValueEvaluationContext evaluationContext = valueContextProvider
.getEvaluationContext(parameters.getBindableParameterValues(), query.getExpressionDependencies());

return query.bindQuery(parameters,
expression -> expression.evaluate(evaluationContext));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
* @author Mark Paluch
* @since 2.6
*/
interface LdapParameterAccessor extends ParameterAccessor {
public interface LdapParameterAccessor extends ParameterAccessor {

/**
* Returns the bindable parameter values of the underlying query method.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import org.springframework.data.ldap.repository.Query;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.query.Parameters;
import org.springframework.data.repository.query.ParametersSource;
import org.springframework.data.repository.query.QueryMethod;
import org.springframework.lang.Nullable;

Expand Down Expand Up @@ -85,4 +87,5 @@ Query getRequiredQueryAnnotation() {

throw new IllegalStateException("Required @Query annotation is not present");
}

}
Loading