Skip to content

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

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
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
2 changes: 1 addition & 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-jpa</artifactId>
<version>1.9.0.BUILD-SNAPSHOT</version>
<version>1.9.0.DATAJPA-218-SNAPSHOT</version>

<name>Spring Data JPA</name>
<description>Spring Data module for JPA repositories.</description>
Expand Down
138 changes: 138 additions & 0 deletions src/main/java/org/springframework/data/jpa/domain/Example.java
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
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;

Expand Down Expand Up @@ -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();

Expand All @@ -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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
Expand All @@ -37,12 +38,16 @@
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;
Expand All @@ -54,6 +59,7 @@
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
Expand Down Expand Up @@ -411,6 +417,38 @@ public List<T> findAll(Specification<T> spec, Sort sort) {
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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,10 @@ public Date getDateOfBirth() {
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}

public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}

/*
* (non-Javadoc)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -55,6 +57,7 @@
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;
Expand Down Expand Up @@ -1904,6 +1907,41 @@ public void accept(User user) {

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) {

Expand Down