DATAJPA-218 - Support extracting parameters from a bean parameter.

Added prototypic support for query by example queries to
SimpleJpaRepositories. Clients can use an Example object to
wrap an existing prototype entity instance that will be used to
derive a query from.

Related tickets: DATACMNS-810.
Original pull request: #164.
This commit is contained in:
Thomas Darimont
2015-07-02 00:18:17 +02:00
committed by Oliver Gierke
parent a1509f9517
commit 6ec173bc9a
5 changed files with 231 additions and 1 deletions

View File

@@ -0,0 +1,138 @@
/*
* Copyright 2015 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
*
* http://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.jpa.domain;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.springframework.util.Assert;
/**
* A wrapper around a prototype object that can be used in <quote>Query by Example<quote> queries
*
* @author Thomas Darimont
* @param <T>
*/
public class Example<T> {
private final T prototype;
private final Set<String> ignoredAttributes;
/**
* Creates a new {@link Example} with the given {@code prototype}.
*
* @param prototype must not be {@literal null}
*/
public Example(T prototype) {
this(prototype, Collections.<String> emptySet());
}
/**
* Creates a new {@link Example} with the given {@code prototype} ignoring the given attributes.
*
* @param prototype prototype must not be {@literal null}
* @param attributeNames prototype must not be {@literal null}
*/
public Example(T prototype, Set<String> attributeNames) {
Assert.notNull(prototype, "Prototype must not be null!");
Assert.notNull(attributeNames, "attributeNames must not be null!");
this.prototype = prototype;
this.ignoredAttributes = attributeNames;
}
public T getPrototype() {
return prototype;
}
public Set<String> getIgnoredAttributes() {
return Collections.unmodifiableSet(ignoredAttributes);
}
public boolean isAttributeIgnored(String attributePath) {
return ignoredAttributes.contains(attributePath);
}
public static <T> Example<T> exampleOf(T prototype) {
return new Example<T>(prototype);
}
public static <T> Builder<T> newExample(T prototype) {
return new Builder<T>(prototype);
}
/**
* A {@link Builder} for {@link Example}s.
*
* @author Thomas Darimont
* @param <T>
*/
public static class Builder<T> {
private final T prototype;
private Set<String> ignoredAttributeNames;
/**
* @param prototype
*/
public Builder(T prototype) {
Assert.notNull(prototype, "Prototype must not be null!");
this.prototype = prototype;
}
/**
* Allows to specify attribute names that should be ignored.
*
* @param attributeNames
* @return
*/
public Builder<T> ignoring(String... attributeNames) {
Assert.notNull(attributeNames, "attributeNames must not be null!");
return ignoring(Arrays.asList(attributeNames));
}
/**
* Allows to specify attribute names that should be ignored.
*
* @param attributeNames
* @return
*/
public Builder<T> ignoring(Collection<String> attributeNames) {
Assert.notNull(attributeNames, "attributeNames must not be null!");
this.ignoredAttributeNames = new HashSet<String>(attributeNames);
return this;
}
/**
* Constructs the actual {@link Example} instance.
*
* @return
*/
public Example<T> build() {
return new Example<T>(prototype, ignoredAttributeNames);
}
}
}

View File

@@ -21,6 +21,7 @@ import java.util.List;
import javax.persistence.EntityManager;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Example;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
@@ -78,7 +79,7 @@ public interface JpaRepository<T, ID extends Serializable> extends PagingAndSort
void deleteInBatch(Iterable<T> entities);
/**
* Deletes all entites in a batch call.
* Deletes all entities in a batch call.
*/
void deleteAllInBatch();
@@ -90,4 +91,15 @@ public interface JpaRepository<T, ID extends Serializable> extends PagingAndSort
* @see EntityManager#getReference(Class, Object)
*/
T getOne(ID id);
/**
* Returns all instances of the type specified by the given {@link Example}.
*
* This method is deliberately <b>not<b> named {@code findByExample} to not interfere
* with existing repository methods that rely on query derivation.
*
* @param example must not be {@literal null}.
* @return
*/
List<T> findWithExample(Example<T> example);
}

View File

@@ -19,6 +19,7 @@ import static org.springframework.data.jpa.repository.query.QueryUtils.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -37,12 +38,16 @@ import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.Attribute;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Example;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.provider.PersistenceProvider;
import org.springframework.data.jpa.repository.EntityGraph;
@@ -54,6 +59,7 @@ import org.springframework.data.jpa.repository.query.QueryUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* Default implementation of the {@link org.springframework.data.repository.CrudRepository} interface. This will offer
@@ -411,6 +417,38 @@ public class SimpleJpaRepository<T, ID extends Serializable> implements JpaRepos
return getQuery(spec, sort).getResultList();
}
/* (non-Javadoc)
* @see org.springframework.data.jpa.repository.JpaRepository#findWithExample(org.springframework.data.jpa.domain.Example)
*/
public List<T> findWithExample(Example<T> example) {
Assert.notNull(example, "Example must not be null!");
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<T> query = builder.createQuery(getDomainClass());
Root<T> root = query.from(getDomainClass());
BeanWrapper bean = new BeanWrapperImpl(example.getPrototype());
List<Predicate> predicates = new ArrayList<Predicate>();
for (Attribute<?, ?> attribute : em.getMetamodel().managedType(getDomainClass()).getAttributes()) {
Object value = bean.getPropertyValue(attribute.getName());
// TODO support different matching modes configured on the provided Example
if (value == null //
|| (value instanceof Collection && CollectionUtils.isEmpty((Collection<?>) value))
|| (value instanceof Map && CollectionUtils.isEmpty((Map<?, ?>) value))
|| example.isAttributeIgnored(attribute.getName())) {
continue;
}
predicates.add(builder.equal(root.get(attribute.getName()), value));
}
return em.createQuery(query.where(predicates.toArray(new Predicate[predicates.size()]))).getResultList();
}
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#count()

View File

@@ -381,6 +381,10 @@ public class User {
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
/*
* (non-Javadoc)

View File

@@ -16,9 +16,11 @@
package org.springframework.data.jpa.repository;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.*;
import static org.springframework.data.domain.Sort.Direction.*;
import static org.springframework.data.jpa.domain.Specifications.*;
import static org.springframework.data.jpa.domain.Specifications.not;
import static org.springframework.data.jpa.domain.sample.UserSpecifications.*;
import java.util.ArrayList;
@@ -55,6 +57,7 @@ import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Example;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.sample.Address;
import org.springframework.data.jpa.domain.sample.Role;
@@ -1904,6 +1907,41 @@ public class UserRepositoryTests {
assertThat(users, hasSize(2));
}
/**
* @see DATAJPA-218
*/
@Test
public void queryByExample() {
flushTestUsers();
User prototype = new User();
prototype.setAge(28);
prototype.setCreatedAt(null);
List<User> users = repository.findWithExample(Example.exampleOf(prototype));
assertThat(users, hasSize(1));
assertThat(users.get(0), is(firstUser));
}
/**
* @see DATAJPA-218
*/
@Test
public void queryByExampleWithExcludedAttributes() {
flushTestUsers();
User prototype = new User();
prototype.setAge(28);
List<User> users = repository.findWithExample(Example.newExample(prototype).ignoring("createdAt").build());
assertThat(users, hasSize(1));
assertThat(users.get(0), is(firstUser));
}
private Page<User> executeSpecWithSort(Sort sort) {