Search in sources :

Example 1 with Example

use of org.springframework.data.domain.Example in project spring-data-jdbc by spring-projects.

the class RelationalExampleMapper method getMappedExample.

/**
 * Transform each property of the {@link Example}'s probe into a {@link Criteria} and assemble them into a
 * {@link Query}.
 *
 * @param example
 * @param entity
 * @return query
 */
private <T> Query getMappedExample(Example<T> example, RelationalPersistentEntity<?> entity) {
    Assert.notNull(example, "Example must not be null!");
    Assert.notNull(entity, "RelationalPersistentEntity must not be null!");
    PersistentPropertyAccessor<T> propertyAccessor = entity.getPropertyAccessor(example.getProbe());
    ExampleMatcherAccessor matcherAccessor = new ExampleMatcherAccessor(example.getMatcher());
    final List<Criteria> criteriaBasedOnProperties = new ArrayList<>();
    entity.doWithProperties((PropertyHandler<RelationalPersistentProperty>) property -> {
        if (matcherAccessor.isIgnoredPath(property.getName())) {
            return;
        }
        Optional<?> optionalConvertedPropValue = matcherAccessor.getValueTransformerForPath(property.getName()).apply(Optional.ofNullable(propertyAccessor.getProperty(property)));
        if (!optionalConvertedPropValue.isPresent()) {
            return;
        }
        Object convPropValue = optionalConvertedPropValue.get();
        boolean ignoreCase = matcherAccessor.isIgnoreCaseForPath(property.getName());
        String column = property.getName();
        switch(matcherAccessor.getStringMatcherForPath(property.getName())) {
            case DEFAULT:
            case EXACT:
                criteriaBasedOnProperties.add(includeNulls(example) ? Criteria.where(column).isNull().or(column).is(convPropValue).ignoreCase(ignoreCase) : Criteria.where(column).is(convPropValue).ignoreCase(ignoreCase));
                break;
            case ENDING:
                criteriaBasedOnProperties.add(includeNulls(example) ? Criteria.where(column).isNull().or(column).like("%" + convPropValue).ignoreCase(ignoreCase) : Criteria.where(column).like("%" + convPropValue).ignoreCase(ignoreCase));
                break;
            case STARTING:
                criteriaBasedOnProperties.add(includeNulls(example) ? Criteria.where(column).isNull().or(column).like(convPropValue + "%").ignoreCase(ignoreCase) : Criteria.where(column).like(convPropValue + "%").ignoreCase(ignoreCase));
                break;
            case CONTAINING:
                criteriaBasedOnProperties.add(includeNulls(example) ? Criteria.where(column).isNull().or(column).like("%" + convPropValue + "%").ignoreCase(ignoreCase) : Criteria.where(column).like("%" + convPropValue + "%").ignoreCase(ignoreCase));
                break;
            default:
                throw new IllegalStateException(example.getMatcher().getDefaultStringMatcher() + " is not supported!");
        }
    });
    // Criteria, assemble!
    Criteria criteria = Criteria.empty();
    for (Criteria propertyCriteria : criteriaBasedOnProperties) {
        if (example.getMatcher().isAllMatching()) {
            criteria = criteria.and(propertyCriteria);
        } else {
            criteria = criteria.or(propertyCriteria);
        }
    }
    return Query.query(criteria);
}
Also used : Query(org.springframework.data.relational.core.query.Query) MappingContext(org.springframework.data.mapping.context.MappingContext) ExampleMatcher(org.springframework.data.domain.ExampleMatcher) Example(org.springframework.data.domain.Example) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) ArrayList(java.util.ArrayList) PropertyHandler(org.springframework.data.mapping.PropertyHandler) ExampleMatcherAccessor(org.springframework.data.support.ExampleMatcherAccessor) List(java.util.List) Optional(java.util.Optional) Criteria(org.springframework.data.relational.core.query.Criteria) RelationalPersistentEntity(org.springframework.data.relational.core.mapping.RelationalPersistentEntity) RelationalPersistentProperty(org.springframework.data.relational.core.mapping.RelationalPersistentProperty) Assert(org.springframework.util.Assert) Optional(java.util.Optional) ArrayList(java.util.ArrayList) ExampleMatcherAccessor(org.springframework.data.support.ExampleMatcherAccessor) Criteria(org.springframework.data.relational.core.query.Criteria) RelationalPersistentProperty(org.springframework.data.relational.core.mapping.RelationalPersistentProperty)

Example 2 with Example

use of org.springframework.data.domain.Example in project spring-data-mongodb by spring-projects.

the class SimpleReactiveMongoRepository method findOne.

// -------------------------------------------------------------------------
// Methods from ReactiveMongoRepository
// -------------------------------------------------------------------------
/*
	 * (non-Javadoc)
	 * @see org.springframework.data.repository.query.ReactiveQueryByExampleExecutor#findOne(org.springframework.data.domain.Example)
	 */
@Override
public <S extends T> Mono<S> findOne(Example<S> example) {
    Assert.notNull(example, "Sample must not be null!");
    Query query = // 
    new Query(new Criteria().alike(example)).collation(// 
    entityInformation.getCollation()).limit(2);
    return mongoOperations.find(query, example.getProbeType(), entityInformation.getCollectionName()).buffer(2).map(vals -> {
        if (vals.size() > 1) {
            throw new IncorrectResultSizeDataAccessException(1);
        }
        return vals.iterator().next();
    }).next();
}
Also used : IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) FluentQuery(org.springframework.data.repository.query.FluentQuery) UnaryOperator(java.util.function.UnaryOperator) Function(java.util.function.Function) OptimisticLockingFailureException(org.springframework.dao.OptimisticLockingFailureException) ReactiveMongoOperations(org.springframework.data.mongodb.core.ReactiveMongoOperations) Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort) ReactiveMongoRepository(org.springframework.data.mongodb.repository.ReactiveMongoRepository) StreamUtils(org.springframework.data.util.StreamUtils) Collection(java.util.Collection) Publisher(org.reactivestreams.Publisher) ReactiveFindOperation(org.springframework.data.mongodb.core.ReactiveFindOperation) MongoEntityInformation(org.springframework.data.mongodb.repository.query.MongoEntityInformation) Mono(reactor.core.publisher.Mono) Example(org.springframework.data.domain.Example) Page(org.springframework.data.domain.Page) Collectors(java.util.stream.Collectors) Criteria(org.springframework.data.mongodb.core.query.Criteria) Serializable(java.io.Serializable) Query(org.springframework.data.mongodb.core.query.Query) Flux(reactor.core.publisher.Flux) List(java.util.List) Streamable(org.springframework.data.util.Streamable) DeleteResult(com.mongodb.client.result.DeleteResult) Collections(java.util.Collections) Assert(org.springframework.util.Assert) FluentQuery(org.springframework.data.repository.query.FluentQuery) Query(org.springframework.data.mongodb.core.query.Query) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) Criteria(org.springframework.data.mongodb.core.query.Criteria)

Example 3 with Example

use of org.springframework.data.domain.Example in project spring-data-jdbc by spring-projects.

the class RelationalExampleMapperTests method queryByExampleSupportsPropertyTransforms.

// GH-929
@Test
void queryByExampleSupportsPropertyTransforms() {
    Person person = new Person();
    person.setFirstname("Frodo");
    person.setLastname("Baggins");
    person.setSecret("I have the ring!");
    ExampleMatcher matcher = // 
    matching().withTransformer("firstname", o -> {
        if (o.isPresent()) {
            return o.map(o1 -> ((String) o1).toUpperCase());
        }
        return o;
    }).withTransformer("lastname", o -> {
        if (o.isPresent()) {
            return o.map(o1 -> ((String) o1).toLowerCase());
        }
        return o;
    });
    Example<Person> example = Example.of(person, matcher);
    Query query = exampleMapper.getMappedExample(example);
    // 
    assertThat(query.getCriteria().map(Object::toString).get()).contains(// 
    "(firstname = 'FRODO')", // 
    " AND ", // 
    "(lastname = 'baggins')", "(secret = 'I have the ring!')");
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) StringMatcher(org.springframework.data.domain.ExampleMatcher.StringMatcher) RelationalMappingContext(org.springframework.data.relational.core.mapping.RelationalMappingContext) GenericPropertyMatchers(org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers) Query(org.springframework.data.relational.core.query.Query) ExampleMatcher(org.springframework.data.domain.ExampleMatcher) Example(org.springframework.data.domain.Example) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) Data(lombok.Data) Assertions(org.assertj.core.api.Assertions) AllArgsConstructor(lombok.AllArgsConstructor) Id(org.springframework.data.annotation.Id) NoArgsConstructor(lombok.NoArgsConstructor) Query(org.springframework.data.relational.core.query.Query) ExampleMatcher(org.springframework.data.domain.ExampleMatcher) Test(org.junit.jupiter.api.Test)

Aggregations

Example (org.springframework.data.domain.Example)3 List (java.util.List)2 ExampleMatcher (org.springframework.data.domain.ExampleMatcher)2 Query (org.springframework.data.relational.core.query.Query)2 Assert (org.springframework.util.Assert)2 DeleteResult (com.mongodb.client.result.DeleteResult)1 Serializable (java.io.Serializable)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 Objects (java.util.Objects)1 Optional (java.util.Optional)1 Function (java.util.function.Function)1 UnaryOperator (java.util.function.UnaryOperator)1 Collectors (java.util.stream.Collectors)1 AllArgsConstructor (lombok.AllArgsConstructor)1 Data (lombok.Data)1 NoArgsConstructor (lombok.NoArgsConstructor)1 Assertions (org.assertj.core.api.Assertions)1 BeforeEach (org.junit.jupiter.api.BeforeEach)1