Skip to content

Add support for providing default Querydsl bindings #2292

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 2 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
6 changes: 4 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.5.0-SNAPSHOT</version>
<version>2.5.0-GH-206-SNAPSHOT</version>

<name>Spring Data Core</name>

Expand Down
2 changes: 2 additions & 0 deletions src/main/asciidoc/repositories.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -1667,6 +1667,8 @@ interface UserRepository extends CrudRepository<User, String>,
<5> Exclude the `password` property from `Predicate` resolution.
====

Additionally, you can register a `DefaultQuerydslBinderCustomizer` bean to apply default Querydsl bindings before applying specific bindings from the repository or `@QuerydslPredicate`.

[[core.repository-populators]]
=== Repository Populators

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright 2021 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
*
* https://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.querydsl.binding;

import com.querydsl.core.types.EntityPath;

/**
* A component for {@link QuerydslBindings} customization acting as default customizer the given entity path regardless
* of the domain type. Instances can be registered with the application context to be applied.
*
* @author Mark Paluch
* @since 2.5
*/
public interface DefaultQuerydslBinderCustomizer extends QuerydslBinderCustomizer<EntityPath<?>> {}
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
*/
package org.springframework.data.querydsl.binding;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
Expand All @@ -37,6 +39,7 @@
*
* @author Oliver Gierke
* @author Christoph Strobl
* @author Mark Paluch
* @since 1.11
*/
public class QuerydslBindingsFactory implements ApplicationContextAware {
Expand All @@ -48,6 +51,7 @@ public class QuerydslBindingsFactory implements ApplicationContextAware {

private Optional<AutowireCapableBeanFactory> beanFactory;
private Optional<Repositories> repositories;
private QuerydslBinderCustomizer<EntityPath<?>> defaultCustomizer;

/**
* Creates a new {@link QuerydslBindingsFactory} using the given {@link EntityPathResolver}.
Expand All @@ -62,6 +66,7 @@ public QuerydslBindingsFactory(EntityPathResolver entityPathResolver) {
this.entityPaths = new ConcurrentReferenceHashMap<>();
this.beanFactory = Optional.empty();
this.repositories = Optional.empty();
this.defaultCustomizer = NoOpCustomizer.INSTANCE;
}

/*
Expand All @@ -73,6 +78,7 @@ public void setApplicationContext(ApplicationContext applicationContext) throws

this.beanFactory = Optional.of(applicationContext.getAutowireCapableBeanFactory());
this.repositories = Optional.of(new Repositories(applicationContext));
this.defaultCustomizer = findDefaultCustomizer();
}

/**
Expand Down Expand Up @@ -126,6 +132,7 @@ private QuerydslBindings createBindingsFor(TypeInformation<?> domainType,
EntityPath<?> path = verifyEntityPathPresent(domainType);

QuerydslBindings bindings = new QuerydslBindings();
defaultCustomizer.customize(bindings, path);
findCustomizerForDomainType(customizer, domainType.getType()).customize(bindings, path);

return bindings;
Expand All @@ -151,9 +158,32 @@ private EntityPath<?> verifyEntityPathPresent(TypeInformation<?> candidate) {
});
}

/**
* Obtains registered {@link DefaultQuerydslBinderCustomizer} instances from the
* {@link org.springframework.beans.factory.BeanFactory}.
*
* @return
*/
private QuerydslBinderCustomizer<EntityPath<?>> findDefaultCustomizer() {
return beanFactory.map(this::getDefaultQuerydslBinderCustomizer).orElse(NoOpCustomizer.INSTANCE);
}

private QuerydslBinderCustomizer<EntityPath<?>> getDefaultQuerydslBinderCustomizer(
AutowireCapableBeanFactory beanFactory) {

List<DefaultQuerydslBinderCustomizer> customizers = beanFactory
.getBeanProvider(DefaultQuerydslBinderCustomizer.class).stream().collect(Collectors.toList());

return (bindings, root) -> {
for (DefaultQuerydslBinderCustomizer defaultQuerydslBinderCustomizer : customizers) {
defaultQuerydslBinderCustomizer.customize(bindings, root);
}
};
}

/**
* Obtains the {@link QuerydslBinderCustomizer} for the given domain type. Will inspect the given annotation for a
* dedicatedly configured one or consider the domain types's repository.
* dedicated configured one or consider the domain type's repository.
*
* @param annotation
* @param domainType
Expand Down Expand Up @@ -194,7 +224,7 @@ private QuerydslBinderCustomizer<EntityPath<?>> createQuerydslBinderCustomizer(
}).orElseGet(() -> BeanUtils.instantiateClass(type));
}

private static enum NoOpCustomizer implements QuerydslBinderCustomizer<EntityPath<?>> {
private enum NoOpCustomizer implements QuerydslBinderCustomizer<EntityPath<?>> {

INSTANCE;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.data.querydsl.QUser;
import org.springframework.data.querydsl.SimpleEntityPathResolver;
import org.springframework.data.querydsl.User;
Expand All @@ -33,6 +35,7 @@
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.servlet.ModelAndView;

import com.querydsl.core.types.EntityPath;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.Predicate;

Expand Down Expand Up @@ -95,6 +98,27 @@ void shouldReuseExistingQuerydslBinderCustomizer() {
});
}

@Test // #206
@SuppressWarnings({ "unchecked", "rawtypes" })
void shouldApplyDefaultCustomizers() {

GenericApplicationContext context = new GenericApplicationContext();
context.registerBean(DefaultCustomizer.class);
context.refresh();

QuerydslBindingsFactory factory = new QuerydslBindingsFactory(SimpleEntityPathResolver.INSTANCE);
factory.setApplicationContext(context);

QuerydslBindings bindings = factory.createBindingsFor(USER_TYPE, SpecificBinding.class);
Optional<MultiValueBinding<Path<Object>, Object>> binding = bindings
.getBindingForPath(PropertyPathInformation.of("inceptionYear", User.class));

assertThat(binding).hasValueSatisfying(it -> {
Optional<Predicate> bind = it.bind((Path) QUser.user.inceptionYear, Collections.singleton(1L));
assertThat(bind).hasValue(QUser.user.inceptionYear.gt(1L));
});
}

@Test // DATACMNS-669
void rejectsPredicateResolutionIfDomainTypeCantBeAutoDetected() {

Expand Down Expand Up @@ -123,4 +147,14 @@ public void customize(QuerydslBindings bindings, QUser user) {
bindings.bind(QUser.user.firstname).firstOptional((path, value) -> value.map(path::contains));
}
}

static class DefaultCustomizer implements DefaultQuerydslBinderCustomizer {

@Override
public void customize(QuerydslBindings bindings, EntityPath<?> root) {

bindings.bind(QUser.user.inceptionYear).first((path, value) -> QUser.user.inceptionYear.gt(value));
}
}

}