diff --git a/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java b/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java index 29e0715fa..c36cdf734 100644 --- a/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/UserRepositoryTests.java @@ -1,2186 +1,2207 @@ -/* - * Copyright 2008-2017 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.repository; - -import static org.hamcrest.Matchers.*; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.*; -import static org.springframework.data.domain.Example.*; -import static org.springframework.data.domain.ExampleMatcher.*; -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; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Stream; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; - -import org.hamcrest.Matchers; -import org.hibernate.Version; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataAccessException; -import org.springframework.dao.IncorrectResultSizeDataAccessException; -import org.springframework.dao.InvalidDataAccessApiUsageException; -import org.springframework.data.domain.Example; -import org.springframework.data.domain.ExampleMatcher; -import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatcher; -import org.springframework.data.domain.ExampleMatcher.StringMatcher; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -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.Specification; -import org.springframework.data.jpa.domain.sample.Address; -import org.springframework.data.jpa.domain.sample.Role; -import org.springframework.data.jpa.domain.sample.SpecialUser; -import org.springframework.data.jpa.domain.sample.User; -import org.springframework.data.jpa.provider.PersistenceProvider; -import org.springframework.data.jpa.repository.sample.SampleEvaluationContextExtension.SampleSecurityContextHolder; -import org.springframework.data.jpa.repository.sample.UserRepository; -import org.springframework.data.jpa.repository.sample.UserRepository.NameOnly; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.transaction.annotation.Transactional; - -import com.google.common.base.Optional; - -/** - * Base integration test class for {@code UserRepository}. Loads a basic (non-namespace) Spring configuration file as - * well as Hibernate configuration to execute tests. - *

- * To test further persistence providers subclass this class and provide a custom provider configuration. - * - * @author Oliver Gierke - * @author Kevin Raymond - * @author Thomas Darimont - * @author Mark Paluch - * @author Jens Schauder - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:application-context.xml") -@Transactional -public class UserRepositoryTests { - - @PersistenceContext EntityManager em; - - // CUT - @Autowired UserRepository repository; - - // Test fixture - User firstUser, secondUser, thirdUser, fourthUser; - Integer id; - Role adminRole; - - @Before - public void setUp() throws Exception { - - firstUser = new User("Oliver", "Gierke", "gierke@synyx.de"); - firstUser.setAge(28); - secondUser = new User("Joachim", "Arrasz", "arrasz@synyx.de"); - secondUser.setAge(35); - Thread.sleep(10); - thirdUser = new User("Dave", "Matthews", "no@email.com"); - thirdUser.setAge(43); - fourthUser = new User("kevin", "raymond", "no@gmail.com"); - fourthUser.setAge(31); - adminRole = new Role("admin"); - - SampleSecurityContextHolder.clear(); - } - - @Test - public void testCreation() { - - Query countQuery = em.createQuery("select count(u) from User u"); - Long before = (Long) countQuery.getSingleResult(); - - flushTestUsers(); - - assertThat((Long) countQuery.getSingleResult(), is(before + 4)); - } - - @Test - public void testRead() throws Exception { - - flushTestUsers(); - - User foundPerson = repository.findOne(id); - assertThat(firstUser.getFirstname(), is(foundPerson.getFirstname())); - } - - @Test - public void findsAllByGivenIds() { - - flushTestUsers(); - - Iterable result = repository.findAll(Arrays.asList(firstUser.getId(), secondUser.getId())); - assertThat(result, hasItems(firstUser, secondUser)); - } - - @Test - public void testReadByIdReturnsNullForNotFoundEntities() { - - flushTestUsers(); - - assertThat(repository.findOne(id * 27), is(nullValue())); - } - - @Test - public void savesCollectionCorrectly() throws Exception { - - List result = repository.save(Arrays.asList(firstUser, secondUser, thirdUser)); - assertThat(result, is(notNullValue())); - assertThat(result.size(), is(3)); - assertThat(result, hasItems(firstUser, secondUser, thirdUser)); - } - - @Test - public void savingNullCollectionIsNoOp() throws Exception { - - List result = repository.save((Collection) null); - assertThat(result, is(notNullValue())); - assertThat(result.isEmpty(), is(true)); - } - - @Test - public void savingEmptyCollectionIsNoOp() throws Exception { - - List result = repository.save(new ArrayList()); - assertThat(result, is(notNullValue())); - assertThat(result.isEmpty(), is(true)); - } - - @Test - public void testUpdate() { - - flushTestUsers(); - - User foundPerson = repository.findOne(id); - foundPerson.setLastname("Schlicht"); - - User updatedPerson = repository.findOne(id); - assertThat(updatedPerson.getFirstname(), is(foundPerson.getFirstname())); - } - - @Test - public void existReturnsWhetherAnEntityCanBeLoaded() throws Exception { - - flushTestUsers(); - assertThat(repository.exists(id), is(true)); - assertThat(repository.exists(id * 27), is(false)); - } - - @Test - public void deletesAUserById() { - - flushTestUsers(); - - repository.delete(firstUser.getId()); - assertThat(repository.exists(id), is(false)); - assertThat(repository.findOne(id), is(nullValue())); - } - - @Test - public void testDelete() { - - flushTestUsers(); - - repository.delete(firstUser); - assertThat(repository.exists(id), is(false)); - assertThat(repository.findOne(id), is(nullValue())); - } - - @Test - public void returnsAllSortedCorrectly() throws Exception { - - flushTestUsers(); - List result = repository.findAll(new Sort(ASC, "lastname")); - assertThat(result, is(notNullValue())); - assertThat(result.size(), is(4)); - assertThat(result.get(0), is(secondUser)); - assertThat(result.get(1), is(firstUser)); - assertThat(result.get(2), is(thirdUser)); - assertThat(result.get(3), is(fourthUser)); - } - - @Test // DATAJPA-296 - public void returnsAllIgnoreCaseSortedCorrectly() throws Exception { - - flushTestUsers(); - - Order order = new Order(ASC, "firstname").ignoreCase(); - List result = repository.findAll(new Sort(order)); - - assertThat(result, is(notNullValue())); - assertThat(result.size(), is(4)); - assertThat(result.get(0), is(thirdUser)); - assertThat(result.get(1), is(secondUser)); - assertThat(result.get(2), is(fourthUser)); - assertThat(result.get(3), is(firstUser)); - } - - @Test - public void deleteColletionOfEntities() { - - flushTestUsers(); - - long before = repository.count(); - - repository.delete(Arrays.asList(firstUser, secondUser)); - assertThat(repository.exists(firstUser.getId()), is(false)); - assertThat(repository.exists(secondUser.getId()), is(false)); - assertThat(repository.count(), is(before - 2)); - } - - @Test - public void batchDeleteColletionOfEntities() { - - flushTestUsers(); - - long before = repository.count(); - - repository.deleteInBatch(Arrays.asList(firstUser, secondUser)); - assertThat(repository.exists(firstUser.getId()), is(false)); - assertThat(repository.exists(secondUser.getId()), is(false)); - assertThat(repository.count(), is(before - 2)); - } - - @Test - public void deleteEmptyCollectionDoesNotDeleteAnything() { - - assertDeleteCallDoesNotDeleteAnything(new ArrayList()); - } - - @Test - public void executesManipulatingQuery() throws Exception { - - flushTestUsers(); - repository.renameAllUsersTo("newLastname"); - - long expected = repository.count(); - assertThat(repository.findByLastname("newLastname").size(), is(Long.valueOf(expected).intValue())); - } - - @Test - public void testFinderInvocationWithNullParameter() { - - flushTestUsers(); - - repository.findByLastname((String) null); - } - - @Test - public void testFindByLastname() throws Exception { - - flushTestUsers(); - - List byName = repository.findByLastname("Gierke"); - - assertThat(byName.size(), is(1)); - assertThat(byName.get(0), is(firstUser)); - } - - /** - * Tests, that searching by the email address of the reference user returns exactly that instance. - * - * @throws Exception - */ - @Test - public void testFindByEmailAddress() throws Exception { - - flushTestUsers(); - - User byName = repository.findByEmailAddress("gierke@synyx.de"); - - assertThat(byName, is(notNullValue())); - assertThat(byName, is(firstUser)); - } - - /** - * Tests reading all users. - */ - @Test - public void testReadAll() { - - flushTestUsers(); - - assertThat(repository.count(), is(4L)); - assertThat(repository.findAll(), hasItems(firstUser, secondUser, thirdUser, fourthUser)); - } - - /** - * Tests that all users get deleted by triggering {@link UserRepository#deleteAll()}. - * - * @throws Exception - */ - @Test - public void deleteAll() throws Exception { - - flushTestUsers(); - - repository.deleteAll(); - - assertThat(repository.count(), is(0L)); - } - - @Test // DATAJPA-137 - public void deleteAllInBatch() { - - flushTestUsers(); - - repository.deleteAllInBatch(); - - assertThat(repository.count(), is(0L)); - } - - /** - * Tests cascading persistence. - */ - @Test - public void testCascadesPersisting() { - - // Create link prior to persisting - firstUser.addColleague(secondUser); - - // Persist - flushTestUsers(); - - // Fetches first user from database - User firstReferenceUser = repository.findOne(firstUser.getId()); - assertThat(firstReferenceUser, is(firstUser)); - - // Fetch colleagues and assert link - Set colleagues = firstReferenceUser.getColleagues(); - assertThat(colleagues.size(), is(1)); - assertThat(colleagues.contains(secondUser), is(true)); - } - - /** - * Tests, that persisting a relationsship without cascade attributes throws a {@code DataAccessException}. - */ - @Test(expected = DataAccessException.class) - public void testPreventsCascadingRolePersisting() { - - firstUser.addRole(new Role("USER")); - - flushTestUsers(); - } - - /** - * Tests cascading on {@literal merge} operation. - */ - @Test - public void testMergingCascadesCollegueas() { - - firstUser.addColleague(secondUser); - flushTestUsers(); - - firstUser.addColleague(new User("Florian", "Hopf", "hopf@synyx.de")); - firstUser = repository.save(firstUser); - - User reference = repository.findOne(firstUser.getId()); - Set colleagues = reference.getColleagues(); - - assertThat(colleagues, is(notNullValue())); - assertThat(colleagues.size(), is(2)); - } - - @Test - public void testCountsCorrectly() { - - long count = repository.count(); - - User user = new User(); - user.setEmailAddress("gierke@synyx.de"); - repository.save(user); - - assertThat(repository.count() == count + 1, is(true)); - } - - @Test - public void testInvocationOfCustomImplementation() { - - repository.someCustomMethod(new User()); - } - - @Test - public void testOverwritingFinder() { - - repository.findByOverrridingMethod(); - } - - @Test - public void testUsesQueryAnnotation() { - - assertThat(repository.findByAnnotatedQuery("gierke@synyx.de"), is(nullValue())); - } - - @Test - public void testExecutionOfProjectingMethod() { - - flushTestUsers(); - assertThat(repository.countWithFirstname("Oliver").longValue(), is(1L)); - } - - @Test - public void executesSpecificationCorrectly() { - - flushTestUsers(); - assertThat(repository.findAll(where(userHasFirstname("Oliver"))).size(), is(1)); - } - - @Test - public void executesSingleEntitySpecificationCorrectly() throws Exception { - - flushTestUsers(); - assertThat(repository.findOne(userHasFirstname("Oliver")), is(firstUser)); - } - - @Test - public void returnsNullIfNoEntityFoundForSingleEntitySpecification() throws Exception { - - flushTestUsers(); - assertThat(repository.findOne(userHasLastname("Beauford")), is(nullValue())); - } - - @Test(expected = IncorrectResultSizeDataAccessException.class) - public void throwsExceptionForUnderSpecifiedSingleEntitySpecification() { - - flushTestUsers(); - repository.findOne(userHasFirstnameLike("e")); - } - - @Test - public void executesCombinedSpecificationsCorrectly() { - - flushTestUsers(); - Specification spec = where(userHasFirstname("Oliver")).or(userHasLastname("Arrasz")); - assertThat(repository.findAll(spec), hasSize(2)); - } - - @Test // DATAJPA-253 - public void executesNegatingSpecificationCorrectly() { - - flushTestUsers(); - Specification spec = not(userHasFirstname("Oliver")).and(userHasLastname("Arrasz")); - List result = repository.findAll(spec); - - assertThat(result, hasSize(1)); - assertThat(result, hasItem(secondUser)); - } - - @Test - public void executesCombinedSpecificationsWithPageableCorrectly() { - - flushTestUsers(); - Specification spec = where(userHasFirstname("Oliver")).or(userHasLastname("Arrasz")); - - Page users = repository.findAll(spec, new PageRequest(0, 1)); - assertThat(users.getSize(), is(1)); - assertThat(users.hasPrevious(), is(false)); - assertThat(users.getTotalElements(), is(2L)); - } - - @Test - public void executesMethodWithAnnotatedNamedParametersCorrectly() throws Exception { - - firstUser = repository.save(firstUser); - secondUser = repository.save(secondUser); - - assertTrue( - repository.findByLastnameOrFirstname("Oliver", "Arrasz").containsAll(Arrays.asList(firstUser, secondUser))); - } - - @Test - public void executesMethodWithNamedParametersCorrectlyOnMethodsWithQueryCreation() throws Exception { - - firstUser = repository.save(firstUser); - secondUser = repository.save(secondUser); - - List result = repository.findByFirstnameOrLastname("Oliver", "Arrasz"); - assertThat(result.size(), is(2)); - assertThat(result, hasItems(firstUser, secondUser)); - } - - @Test - public void executesLikeAndOrderByCorrectly() throws Exception { - - flushTestUsers(); - - List result = repository.findByLastnameLikeOrderByFirstnameDesc("%r%"); - assertThat(result.size(), is(3)); - assertEquals(fourthUser, result.get(0)); - assertEquals(firstUser, result.get(1)); - assertEquals(secondUser, result.get(2)); - } - - @Test - public void executesNotLikeCorrectly() throws Exception { - - flushTestUsers(); - - List result = repository.findByLastnameNotLike("%er%"); - assertThat(result.size(), is(3)); - assertThat(result, hasItems(secondUser, thirdUser, fourthUser)); - } - - @Test - public void executesSimpleNotCorrectly() throws Exception { - - flushTestUsers(); - - List result = repository.findByLastnameNot("Gierke"); - assertThat(result.size(), is(3)); - assertThat(result, hasItems(secondUser, thirdUser, fourthUser)); - } - - @Test - public void returnsSameListIfNoSpecGiven() throws Exception { - - flushTestUsers(); - assertSameElements(repository.findAll(), repository.findAll((Specification) null)); - } - - @Test - public void returnsSameListIfNoSortIsGiven() throws Exception { - - flushTestUsers(); - assertSameElements(repository.findAll((Sort) null), repository.findAll()); - } - - @Test - public void returnsSamePageIfNoSpecGiven() throws Exception { - - Pageable pageable = new PageRequest(0, 1); - - flushTestUsers(); - assertThat(repository.findAll((Specification) null, pageable), is(repository.findAll(pageable))); - } - - @Test - public void returnsAllAsPageIfNoPageableIsGiven() throws Exception { - - flushTestUsers(); - assertThat(repository.findAll((Pageable) null), is((Page) new PageImpl(repository.findAll()))); - } - - @Test - public void removeDetachedObject() throws Exception { - - flushTestUsers(); - - em.detach(firstUser); - repository.delete(firstUser); - - assertThat(repository.count(), is(3L)); - } - - @Test - public void executesPagedSpecificationsCorrectly() throws Exception { - - Page result = executeSpecWithSort(null); - assertThat(result.getContent(), anyOf(hasItem(firstUser), hasItem(thirdUser))); - assertThat(result.getContent(), not(hasItem(secondUser))); - } - - @Test - public void executesPagedSpecificationsWithSortCorrectly() throws Exception { - - Page result = executeSpecWithSort(new Sort(Direction.ASC, "lastname")); - - assertThat(result.getContent(), hasItem(firstUser)); - assertThat(result.getContent(), not(hasItem(secondUser))); - assertThat(result.getContent(), not(hasItem(thirdUser))); - } - - @Test - public void executesPagedSpecificationWithSortCorrectly2() throws Exception { - - Page result = executeSpecWithSort(new Sort(Direction.DESC, "lastname")); - - assertThat(result.getContent(), hasItem(thirdUser)); - assertThat(result.getContent(), not(hasItem(secondUser))); - assertThat(result.getContent(), not(hasItem(firstUser))); - } - - @Test - public void executesQueryMethodWithDeepTraversalCorrectly() throws Exception { - - flushTestUsers(); - - firstUser.setManager(secondUser); - thirdUser.setManager(firstUser); - repository.save(Arrays.asList(firstUser, thirdUser)); - - List result = repository.findByManagerLastname("Arrasz"); - - assertThat(result.size(), is(1)); - assertThat(result, hasItem(firstUser)); - - result = repository.findByManagerLastname("Gierke"); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(thirdUser)); - } - - @Test - public void executesFindByColleaguesLastnameCorrectly() throws Exception { - - flushTestUsers(); - - firstUser.addColleague(secondUser); - thirdUser.addColleague(firstUser); - repository.save(Arrays.asList(firstUser, thirdUser)); - - List result = repository.findByColleaguesLastname(secondUser.getLastname()); - - assertThat(result.size(), is(1)); - assertThat(result, hasItem(firstUser)); - - result = repository.findByColleaguesLastname("Gierke"); - assertThat(result.size(), is(2)); - assertThat(result, hasItems(thirdUser, secondUser)); - } - - @Test - public void executesFindByNotNullLastnameCorrectly() throws Exception { - - flushTestUsers(); - List result = repository.findByLastnameNotNull(); - - assertThat(result.size(), is(4)); - assertThat(result, hasItems(firstUser, secondUser, thirdUser, fourthUser)); - } - - @Test - public void executesFindByNullLastnameCorrectly() throws Exception { - - flushTestUsers(); - User forthUser = repository.save(new User("Foo", null, "email@address.com")); - - List result = repository.findByLastnameNull(); - - assertThat(result.size(), is(1)); - assertThat(result, hasItems(forthUser)); - } - - @Test - public void findsSortedByLastname() throws Exception { - - flushTestUsers(); - - List result = repository.findByEmailAddressLike("%@%", new Sort(Direction.ASC, "lastname")); - - assertThat(result.size(), is(4)); - assertThat(result.get(0), is(secondUser)); - assertThat(result.get(1), is(firstUser)); - assertThat(result.get(2), is(thirdUser)); - assertThat(result.get(3), is(fourthUser)); - } - - @Test - public void findsUsersBySpringDataNamedQuery() { - - flushTestUsers(); - - List result = repository.findBySpringDataNamedQuery("Gierke"); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(firstUser)); - } - - @Test // DATADOC-86 - public void readsPageWithGroupByClauseCorrectly() { - - flushTestUsers(); - - Page result = repository.findByLastnameGrouped(new PageRequest(0, 10)); - assertThat(result.getTotalPages(), is(1)); - } - - @Test - public void executesLessThatOrEqualQueriesCorrectly() { - - flushTestUsers(); - - List result = repository.findByAgeLessThanEqual(35); - assertThat(result.size(), is(3)); - assertThat(result, hasItems(firstUser, secondUser, fourthUser)); - } - - @Test - public void executesGreaterThatOrEqualQueriesCorrectly() { - - flushTestUsers(); - - List result = repository.findByAgeGreaterThanEqual(35); - assertThat(result.size(), is(2)); - assertThat(result, hasItems(secondUser, thirdUser)); - } - - @Test // DATAJPA-117 - public void executesNativeQueryCorrectly() { - - flushTestUsers(); - - List result = repository.findNativeByLastname("Matthews"); - - assertThat(result, hasItem(thirdUser)); - assertThat(result.size(), is(1)); - } - - @Test // DATAJPA-132 - public void executesFinderWithTrueKeywordCorrectly() { - - flushTestUsers(); - firstUser.setActive(false); - repository.save(firstUser); - - List result = repository.findByActiveTrue(); - assertThat(result.size(), is(3)); - assertThat(result, hasItems(secondUser, thirdUser, fourthUser)); - } - - @Test // DATAJPA-132 - public void executesFinderWithFalseKeywordCorrectly() { - - flushTestUsers(); - firstUser.setActive(false); - repository.save(firstUser); - - List result = repository.findByActiveFalse(); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(firstUser)); - } - - /** - * Ignored until the query declaration is supported by OpenJPA. - */ - @Test - @Ignore - public void executesAnnotatedCollectionMethodCorrectly() { - - flushTestUsers(); - firstUser.addColleague(thirdUser); - repository.save(firstUser); - - List result = null; // repository.findColleaguesFor(firstUser); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(thirdUser)); - } - - @Test // DATAJPA-188 - public void executesFinderWithAfterKeywordCorrectly() { - - flushTestUsers(); - - List result = repository.findByCreatedAtAfter(secondUser.getCreatedAt()); - assertThat(result.size(), is(2)); - assertThat(result, hasItems(thirdUser, fourthUser)); - } - - @Test // DATAJPA-188 - public void executesFinderWithBeforeKeywordCorrectly() { - - flushTestUsers(); - - List result = repository.findByCreatedAtBefore(thirdUser.getCreatedAt()); - assertThat(result.size(), is(2)); - assertThat(result, hasItems(firstUser, secondUser)); - } - - @Test // DATAJPA-180 - public void executesFinderWithStartingWithCorrectly() { - - flushTestUsers(); - List result = repository.findByFirstnameStartingWith("Oli"); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(firstUser)); - } - - @Test // DATAJPA-180 - public void executesFinderWithEndingWithCorrectly() { - - flushTestUsers(); - List result = repository.findByFirstnameEndingWith("er"); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(firstUser)); - } - - @Test // DATAJPA-180 - public void executesFinderWithContainingCorrectly() { - - flushTestUsers(); - List result = repository.findByFirstnameContaining("a"); - assertThat(result.size(), is(2)); - assertThat(result, hasItems(secondUser, thirdUser)); - } - - @Test // DATAJPA-201 - public void allowsExecutingPageableMethodWithNullPageable() { - - flushTestUsers(); - - List users = repository.findByFirstname("Oliver", null); - assertThat(users.size(), is(1)); - assertThat(users, hasItem(firstUser)); - - Page page = repository.findByFirstnameIn(null, "Oliver"); - assertThat(page.getNumberOfElements(), is(1)); - assertThat(page.getContent(), hasItem(firstUser)); - - page = repository.findAll((Pageable) null); - assertThat(page.getNumberOfElements(), is(4)); - assertThat(page.getContent(), hasItems(firstUser, secondUser, thirdUser, fourthUser)); - } - - @Test // DATAJPA-207 - public void executesNativeQueryForNonEntitiesCorrectly() { - - flushTestUsers(); - - List result = repository.findOnesByNativeQuery(); - - assertThat(result.size(), is(4)); - assertThat(result, hasItem(1)); - } - - @Test // DATAJPA-232 - public void handlesIterableOfIdsCorrectly() { - - flushTestUsers(); - - Set set = new HashSet(); - set.add(firstUser.getId()); - set.add(secondUser.getId()); - - Iterable result = repository.findAll(set); - - assertThat(result, is(Matchers. iterableWithSize(2))); - assertThat(result, hasItems(firstUser, secondUser)); - } - - protected void flushTestUsers() { - - em.persist(adminRole); - - firstUser = repository.save(firstUser); - secondUser = repository.save(secondUser); - thirdUser = repository.save(thirdUser); - fourthUser = repository.save(fourthUser); - - repository.flush(); - - id = firstUser.getId(); - - assertThat(id, is(notNullValue())); - assertThat(secondUser.getId(), is(notNullValue())); - assertThat(thirdUser.getId(), is(notNullValue())); - assertThat(fourthUser.getId(), is(notNullValue())); - - assertThat(repository.exists(id), is(true)); - assertThat(repository.exists(secondUser.getId()), is(true)); - assertThat(repository.exists(thirdUser.getId()), is(true)); - assertThat(repository.exists(fourthUser.getId()), is(true)); - } - - private static void assertSameElements(Collection first, Collection second) { - - for (T element : first) { - assertThat(element, isIn(second)); - } - - for (T element : second) { - assertThat(element, isIn(first)); - } - } - - private void assertDeleteCallDoesNotDeleteAnything(List collection) { - - flushTestUsers(); - long count = repository.count(); - - repository.delete(collection); - assertThat(repository.count(), is(count)); - } - - @Test - public void ordersByReferencedEntityCorrectly() { - - flushTestUsers(); - firstUser.setManager(thirdUser); - repository.save(firstUser); - - Page all = repository.findAll(new PageRequest(0, 10, new Sort("manager.id"))); - - assertThat(all.getContent().isEmpty(), is(false)); - } - - @Test // DATAJPA-252 - public void bindsSortingToOuterJoinCorrectly() { - - flushTestUsers(); - - // Managers not set, make sure adding the sort does not rule out those Users - Page result = repository.findAllPaged(new PageRequest(0, 10, new Sort("manager.lastname"))); - assertThat(result.getContent(), hasSize((int) repository.count())); - } - - @Test // DATAJPA-277 - public void doesNotDropNullValuesOnPagedSpecificationExecution() { - - flushTestUsers(); - - Page page = repository.findAll(new Specification() { - public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) { - return cb.equal(root.get("lastname"), "Gierke"); - } - }, new PageRequest(0, 20, new Sort("manager.lastname"))); - - assertThat(page.getNumberOfElements(), is(1)); - assertThat(page, hasItem(firstUser)); - } - - @Test // DATAJPA-346 - public void shouldGenerateLeftOuterJoinInfindAllWithPaginationAndSortOnNestedPropertyPath() { - - firstUser.setManager(null); - secondUser.setManager(null); - thirdUser.setManager(firstUser); // manager Oliver - fourthUser.setManager(secondUser); // manager Joachim - - flushTestUsers(); - - Page pages = repository.findAll(new PageRequest(0, 4, new Sort(Sort.Direction.ASC, "manager.firstname"))); - assertThat(pages.getSize(), is(4)); - assertThat(pages.getContent().get(0).getManager(), is(nullValue())); - assertThat(pages.getContent().get(1).getManager(), is(nullValue())); - assertThat(pages.getContent().get(2).getManager().getFirstname(), is("Joachim")); - assertThat(pages.getContent().get(3).getManager().getFirstname(), is("Oliver")); - assertThat(pages.getTotalElements(), is(4L)); - } - - @Test // DATAJPA-292 - public void executesManualQueryWithPositionLikeExpressionCorrectly() { - - flushTestUsers(); - - List result = repository.findByFirstnameLike("Da"); - - assertThat(result, hasSize(1)); - assertThat(result, hasItem(thirdUser)); - } - - @Test // DATAJPA-292 - public void executesManualQueryWithNamedLikeExpressionCorrectly() { - - flushTestUsers(); - - List result = repository.findByFirstnameLikeNamed("Da"); - - assertThat(result, hasSize(1)); - assertThat(result, hasItem(thirdUser)); - } - - @Test // DATAJPA-231 - public void executesDerivedCountQueryToLong() { - - flushTestUsers(); - - assertThat(repository.countByLastname("Matthews"), is(1L)); - } - - @Test // DATAJPA-231 - public void executesDerivedCountQueryToInt() { - - flushTestUsers(); - - assertThat(repository.countUsersByFirstname("Dave"), is(1)); - } - - @Test // DATAJPA-231 - public void executesDerivedExistsQuery() { - - flushTestUsers(); - - assertThat(repository.existsByLastname("Matthews"), is(true)); - assertThat(repository.existsByLastname("Hans Peter"), is(false)); - } - - @Test // DATAJPA-332 - public void findAllReturnsEmptyIterableIfNoIdsGiven() { - - assertThat(repository.findAll(Collections. emptySet()), is(emptyIterable())); - assertThat(repository.findAll((Iterable) null), is(emptyIterable())); - } - - @Test // DATAJPA-391 - public void executesManuallyDefinedQueryWithFieldProjection() { - - flushTestUsers(); - List lastname = repository.findFirstnamesByLastname("Matthews"); - - assertThat(lastname, hasSize(1)); - assertThat(lastname, hasItem("Dave")); - } - - @Test // DATAJPA-83 - public void looksUpEntityReference() { - - flushTestUsers(); - - User result = repository.getOne(firstUser.getId()); - assertThat(result, is(firstUser)); - } - - @Test // DATAJPA-415 - public void invokesQueryWithVarargsParametersCorrectly() { - - flushTestUsers(); - - Collection result = repository.findByIdIn(firstUser.getId(), secondUser.getId()); - - assertThat(result, hasSize(2)); - assertThat(result, hasItems(firstUser, secondUser)); - } - - @Test // DATAJPA-415 - public void shouldSupportModifyingQueryWithVarArgs() { - - flushTestUsers(); - - repository.updateUserActiveState(false, firstUser.getId(), secondUser.getId(), thirdUser.getId(), - fourthUser.getId()); - - long expectedCount = repository.count(); - assertThat(repository.findByActiveFalse().size(), is((int) expectedCount)); - assertThat(repository.findByActiveTrue().size(), is(0)); - } - - @Test // DATAJPA-405 - public void executesFinderWithOrderClauseOnly() { - - flushTestUsers(); - - List result = repository.findAllByOrderByLastnameAsc(); - - assertThat(result, hasSize(4)); - assertThat(result, contains(secondUser, firstUser, thirdUser, fourthUser)); - } - - @Test // DATAJPA-427 - public void sortByAssociationPropertyShouldUseLeftOuterJoin() { - - secondUser.getColleagues().add(firstUser); - fourthUser.getColleagues().add(thirdUser); - flushTestUsers(); - - List result = repository.findAll(new Sort(Sort.Direction.ASC, "colleagues.id")); - - assertThat(result, hasSize(4)); - } - - @Test // DATAJPA-427 - public void sortByAssociationPropertyInPageableShouldUseLeftOuterJoin() { - - secondUser.getColleagues().add(firstUser); - fourthUser.getColleagues().add(thirdUser); - flushTestUsers(); - - Page page = repository.findAll(new PageRequest(0, 10, new Sort(Sort.Direction.ASC, "colleagues.id"))); - - assertThat(page.getContent(), hasSize(4)); - } - - @Test // DATAJPA-427 - public void sortByEmbeddedProperty() { - - thirdUser.setAddress(new Address("Germany", "Saarbrücken", "HaveItYourWay", "123")); - flushTestUsers(); - - Page page = repository.findAll(new PageRequest(0, 10, new Sort(Sort.Direction.ASC, "address.streetName"))); - - assertThat(page.getContent(), hasSize(4)); - assertThat(page.getContent().get(3), is(thirdUser)); - } - - @Test // DATAJPA-454 - public void findsUserByBinaryDataReference() throws Exception { - - byte[] data = "Woho!!".getBytes("UTF-8"); - firstUser.setBinaryData(data); - - flushTestUsers(); - - List result = repository.findByBinaryData(data); - assertThat(result, hasSize(1)); - assertThat(result, hasItem(firstUser)); - assertThat(result.get(0).getBinaryData(), is(data)); - } - - @Test // DATAJPA-461 - public void customFindByQueryWithPositionalVarargsParameters() { - - flushTestUsers(); - - Collection result = repository.findByIdsCustomWithPositionalVarArgs(firstUser.getId(), secondUser.getId()); - - assertThat(result, hasSize(2)); - assertThat(result, hasItems(firstUser, secondUser)); - } - - @Test // DATAJPA-461 - public void customFindByQueryWithNamedVarargsParameters() { - - flushTestUsers(); - - Collection result = repository.findByIdsCustomWithNamedVarArgs(firstUser.getId(), secondUser.getId()); - - assertThat(result, hasSize(2)); - assertThat(result, hasItems(firstUser, secondUser)); - } - - @Test // DATAJPA-464 - public void saveAndFlushShouldSupportReturningSubTypesOfRepositoryEntity() { - - repository.deleteAll(); - SpecialUser user = new SpecialUser(); - user.setFirstname("Thomas"); - user.setEmailAddress("thomas@example.org"); - - SpecialUser savedUser = repository.saveAndFlush(user); - - assertThat(user.getFirstname(), is(savedUser.getFirstname())); - assertThat(user.getEmailAddress(), is(savedUser.getEmailAddress())); - } - - @Test // DATAJPA-218 - public void findAllByUntypedExampleShouldReturnSubTypesOfRepositoryEntity() { - - flushTestUsers(); - - SpecialUser user = new SpecialUser(); - user.setFirstname("Thomas"); - user.setEmailAddress("thomas@example.org"); - - repository.saveAndFlush(user); - - List result = repository - .findAll(Example.of(new User(), ExampleMatcher.matching().withIgnorePaths("age", "createdAt", "dateOfBirth"))); - - assertThat(result, hasSize(5)); - } - - @Test // DATAJPA-218 - public void findAllByTypedUserExampleShouldReturnSubTypesOfRepositoryEntity() { - - flushTestUsers(); - - SpecialUser user = new SpecialUser(); - user.setFirstname("Thomas"); - user.setEmailAddress("thomas@example.org"); - - repository.saveAndFlush(user); - - Example example = Example.of(new User(), matching().withIgnorePaths("age", "createdAt", "dateOfBirth")); - List result = repository.findAll(example); - - assertThat(result, hasSize(5)); - } - - @Test // DATAJPA-218 - public void findAllByTypedSpecialUserExampleShouldReturnSubTypesOfRepositoryEntity() { - - flushTestUsers(); - - SpecialUser user = new SpecialUser(); - user.setFirstname("Thomas"); - user.setEmailAddress("thomas@example.org"); - - repository.saveAndFlush(user); - - Example example = Example.of(new SpecialUser(), - matching().withIgnorePaths("age", "createdAt", "dateOfBirth")); - List result = repository.findAll(example); - - assertThat(result, hasSize(1)); - } - - @Test // DATAJPA-491 - public void sortByNestedAssociationPropertyWithSortInPageable() { - - firstUser.setManager(thirdUser); - thirdUser.setManager(fourthUser); - - flushTestUsers(); - - Page page = repository.findAll(new PageRequest(0, 10, // - new Sort(Sort.Direction.ASC, "manager.manager.firstname"))); - - assertThat(page.getContent(), hasSize(4)); - assertThat(page.getContent().get(3), is(firstUser)); - } - - @Test // DATAJPA-510 - public void sortByNestedAssociationPropertyWithSortOrderIgnoreCaseInPageable() { - - firstUser.setManager(thirdUser); - thirdUser.setManager(fourthUser); - - flushTestUsers(); - - Page page = repository.findAll(new PageRequest(0, 10, // - new Sort(new Sort.Order(Direction.ASC, "manager.manager.firstname").ignoreCase()))); - - assertThat(page.getContent(), hasSize(4)); - assertThat(page.getContent().get(3), is(firstUser)); - } - - @Test // DATAJPA-496 - public void findByElementCollectionAttribute() { - - firstUser.getAttributes().add("cool"); - secondUser.getAttributes().add("hip"); - thirdUser.getAttributes().add("rockstar"); - - flushTestUsers(); - - List result = repository.findByAttributesIn(new HashSet(Arrays.asList("cool", "hip"))); - - assertThat(result, hasSize(2)); - assertThat(result, hasItems(firstUser, secondUser)); - } - - @Test // DATAJPA-460 - public void deleteByShouldReturnListOfDeletedElementsWhenRetunTypeIsCollectionLike() { - - flushTestUsers(); - - List result = repository.deleteByLastname(firstUser.getLastname()); - assertThat(result, hasItem(firstUser)); - assertThat(result, hasSize(1)); - } - - @Test // DATAJPA-460 - public void deleteByShouldRemoveElementsMatchingDerivedQuery() { - - flushTestUsers(); - - repository.deleteByLastname(firstUser.getLastname()); - assertThat(repository.countByLastname(firstUser.getLastname()), is(0L)); - } - - @Test // DATAJPA-460 - public void deleteByShouldReturnNumberOfEntitiesRemovedIfReturnTypeIsLong() { - - flushTestUsers(); - - assertThat(repository.removeByLastname(firstUser.getLastname()), is(1L)); - } - - @Test // DATAJPA-460 - public void deleteByShouldReturnZeroInCaseNoEntityHasBeenRemovedAndReturnTypeIsNumber() { - - flushTestUsers(); - - assertThat(repository.removeByLastname("bubu"), is(0L)); - } - - @Test // DATAJPA-460 - public void deleteByShouldReturnEmptyListInCaseNoEntityHasBeenRemovedAndReturnTypeIsCollectionLike() { - - flushTestUsers(); - - assertThat(repository.deleteByLastname("dorfuaeB"), empty()); - } - - /** - * @see OPENJPA-2484 - */ - @Test // DATAJPA-505 - @Ignore - public void findBinaryDataByIdJpaQl() throws Exception { - - byte[] data = "Woho!!".getBytes("UTF-8"); - firstUser.setBinaryData(data); - - flushTestUsers(); - - byte[] result = null; // repository.findBinaryDataByIdJpaQl(firstUser.getId()); - - assertThat(result.length, is(data.length)); - assertThat(result, is(data)); - } - - @Test // DATAJPA-506 - public void findBinaryDataByIdNative() throws Exception { - - byte[] data = "Woho!!".getBytes("UTF-8"); - firstUser.setBinaryData(data); - - flushTestUsers(); - - byte[] result = repository.findBinaryDataByIdNative(firstUser.getId()); - assertThat(result.length, is(data.length)); - assertThat(result, is(data)); - } - - @Test // DATAJPA-456 - public void findPaginatedExplicitQueryWithCountQueryProjection() { - - firstUser.setFirstname(null); - - flushTestUsers(); - - Page result = repository.findAllByFirstnameLike("", new PageRequest(0, 10)); - - assertThat(result.getContent().size(), is(3)); - } - - @Test // DATAJPA-456 - public void findPaginatedNamedQueryWithCountQueryProjection() { - - flushTestUsers(); - - Page result = repository.findByNamedQueryAndCountProjection("Gierke", new PageRequest(0, 10)); - - assertThat(result.getContent().size(), is(1)); - } - - @Test // DATAJPA-551 - public void findOldestUser() { - - flushTestUsers(); - - User oldest = thirdUser; - - assertThat(repository.findFirstByOrderByAgeDesc(), is(oldest)); - assertThat(repository.findFirst1ByOrderByAgeDesc(), is(oldest)); - } - - @Test // DATAJPA-551 - public void findYoungestUser() { - - flushTestUsers(); - - User youngest = firstUser; - - assertThat(repository.findTopByOrderByAgeAsc(), is(youngest)); - assertThat(repository.findTop1ByOrderByAgeAsc(), is(youngest)); - } - - @Test // DATAJPA-551 - public void find2OldestUsers() { - - flushTestUsers(); - - User oldest1 = thirdUser; - User oldest2 = secondUser; - - assertThat(repository.findFirst2ByOrderByAgeDesc(), hasItems(oldest1, oldest2)); - assertThat(repository.findTop2ByOrderByAgeDesc(), hasItems(oldest1, oldest2)); - } - - @Test // DATAJPA-551 - public void find2YoungestUsers() { - - flushTestUsers(); - - User youngest1 = firstUser; - User youngest2 = fourthUser; - - assertThat(repository.findFirst2UsersBy(new Sort(ASC, "age")), hasItems(youngest1, youngest2)); - assertThat(repository.findTop2UsersBy(new Sort(ASC, "age")), hasItems(youngest1, youngest2)); - } - - @Test // DATAJPA-551 - public void find3YoungestUsersPageableWithPageSize2() { - - flushTestUsers(); - - User youngest1 = firstUser; - User youngest2 = fourthUser; - User youngest3 = secondUser; - - Page firstPage = repository.findFirst3UsersBy(new PageRequest(0, 2, ASC, "age")); - assertThat(firstPage.getContent(), hasItems(youngest1, youngest2)); - - Page secondPage = repository.findFirst3UsersBy(new PageRequest(1, 2, ASC, "age")); - assertThat(secondPage.getContent(), hasItems(youngest3)); - } - - @Test // DATAJPA-551 - public void find2YoungestUsersPageableWithPageSize3() { - - flushTestUsers(); - - User youngest1 = firstUser; - User youngest2 = fourthUser; - User youngest3 = secondUser; - - Page firstPage = repository.findFirst2UsersBy(new PageRequest(0, 3, ASC, "age")); - assertThat(firstPage.getContent(), hasItems(youngest1, youngest2)); - - Page secondPage = repository.findFirst2UsersBy(new PageRequest(1, 3, ASC, "age")); - assertThat(secondPage.getContent(), hasItems(youngest3)); - } - - @Test // DATAJPA-551 - public void find3YoungestUsersPageableWithPageSize2Sliced() { - - flushTestUsers(); - - User youngest1 = firstUser; - User youngest2 = fourthUser; - User youngest3 = secondUser; - - Slice firstPage = repository.findTop3UsersBy(new PageRequest(0, 2, ASC, "age")); - assertThat(firstPage.getContent(), hasItems(youngest1, youngest2)); - - Slice secondPage = repository.findTop3UsersBy(new PageRequest(1, 2, ASC, "age")); - assertThat(secondPage.getContent(), hasItems(youngest3)); - } - - @Test // DATAJPA-551 - public void find2YoungestUsersPageableWithPageSize3Sliced() { - - flushTestUsers(); - - User youngest1 = firstUser; - User youngest2 = fourthUser; - User youngest3 = secondUser; - - Slice firstPage = repository.findTop2UsersBy(new PageRequest(0, 3, ASC, "age")); - assertThat(firstPage.getContent(), hasItems(youngest1, youngest2)); - - Slice secondPage = repository.findTop2UsersBy(new PageRequest(1, 3, ASC, "age")); - assertThat(secondPage.getContent(), hasItems(youngest3)); - } - - @Test // DATAJPA-912 - public void pageableQueryReportsTotalFromResult() { - - flushTestUsers(); - - Page firstPage = repository.findAll(new PageRequest(0, 10)); - assertThat(firstPage.getContent(), hasSize(4)); - assertThat(firstPage.getTotalElements(), is(4L)); - - Page secondPage = repository.findAll(new PageRequest(1, 3)); - assertThat(secondPage.getContent(), hasSize(1)); - assertThat(secondPage.getTotalElements(), is(4L)); - } - - @Test // DATAJPA-912 - public void pageableQueryReportsTotalFromCount() { - - flushTestUsers(); - - Page firstPage = repository.findAll(new PageRequest(0, 4)); - assertThat(firstPage.getContent(), hasSize(4)); - assertThat(firstPage.getTotalElements(), is(4L)); - - Page secondPage = repository.findAll(new PageRequest(10, 10)); - assertThat(secondPage.getContent(), hasSize(0)); - assertThat(secondPage.getTotalElements(), is(4L)); - } - - @Test // DATAJPA-506 - public void invokesQueryWithWrapperType() { - - flushTestUsers(); - - Optional result = repository.findOptionalByEmailAddress("gierke@synyx.de"); - - assertThat(result.isPresent(), is(true)); - assertThat(result.get(), is(firstUser)); - } - - @Test // DATAJPA-564 - public void shouldFindUserByFirstnameAndLastnameWithSpelExpressionInStringBasedQuery() { - - flushTestUsers(); - List users = repository.findByFirstnameAndLastnameWithSpelExpression("Oliver", "ierk"); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(firstUser)); - } - - @Test // DATAJPA-564 - public void shouldFindUserByLastnameWithSpelExpressionInStringBasedQuery() { - - flushTestUsers(); - List users = repository.findByLastnameWithSpelExpression("ierk"); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(firstUser)); - } - - @Test // DATAJPA-564 - public void shouldFindBySpELExpressionWithoutArgumentsWithQuestionmark() { - - flushTestUsers(); - List users = repository.findOliverBySpELExpressionWithoutArgumentsWithQuestionmark(); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(firstUser)); - } - - @Test // DATAJPA-564 - public void shouldFindBySpELExpressionWithoutArgumentsWithColon() { - - flushTestUsers(); - List users = repository.findOliverBySpELExpressionWithoutArgumentsWithColon(); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(firstUser)); - } - - @Test // DATAJPA-564 - public void shouldFindUsersByAgeForSpELExpression() { - - flushTestUsers(); - List users = repository.findUsersByAgeForSpELExpressionByIndexedParameter(35); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(secondUser)); - } - - @Test // DATAJPA-564 - public void shouldfindUsersByFirstnameForSpELExpressionWithParameterNameVariableReference() { - - flushTestUsers(); - List users = repository.findUsersByFirstnameForSpELExpression("Joachim"); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(secondUser)); - } - - @Test // DATAJPA-564 - public void shouldFindCurrentUserWithCustomQueryDependingOnSecurityContext() { - - flushTestUsers(); - - SampleSecurityContextHolder.getCurrent().setPrincipal(secondUser); - List users = repository.findCurrentUserWithCustomQuery(); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(secondUser)); - - SampleSecurityContextHolder.getCurrent().setPrincipal(firstUser); - users = repository.findCurrentUserWithCustomQuery(); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(firstUser)); - } - - @Test // DATAJPA-564 - public void shouldFindByFirstnameAndCurrentUserWithCustomQuery() { - - flushTestUsers(); - - SampleSecurityContextHolder.getCurrent().setPrincipal(secondUser); - List users = repository.findByFirstnameAndCurrentUserWithCustomQuery("Joachim"); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(secondUser)); - } - - @Test // DATAJPA-564 - public void shouldfindUsersByFirstnameForSpELExpressionOnlyWithParameterNameVariableReference() { - - flushTestUsers(); - List users = repository.findUsersByFirstnameForSpELExpressionWithParameterVariableOnly("Joachim"); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(secondUser)); - } - - @Test // DATAJPA-564 - public void shouldfindUsersByFirstnameForSpELExpressionOnlyWithParameterIndexReference() { - - flushTestUsers(); - List users = repository.findUsersByFirstnameForSpELExpressionWithParameterIndexOnly("Joachim"); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(secondUser)); - } - - @Test // DATAJPA-564 - public void shouldFindUsersInNativeQueryWithPagination() { - - flushTestUsers(); - - Page users = repository.findUsersInNativeQueryWithPagination(new PageRequest(0, 2)); - - assertThat(users.getContent(), hasSize(2)); - assertThat(users.getContent().get(0), is(firstUser)); - assertThat(users.getContent().get(1), is(secondUser)); - - users = repository.findUsersInNativeQueryWithPagination(new PageRequest(1, 2)); - - assertThat(users.getContent(), hasSize(2)); - assertThat(users.getContent().get(0), is(thirdUser)); - assertThat(users.getContent().get(1), is(fourthUser)); - } - - @Test // DATAJPA-629 - public void shouldfindUsersBySpELExpressionParametersWithSpelTemplateExpression() { - - flushTestUsers(); - List users = repository - .findUsersByFirstnameForSpELExpressionWithParameterIndexOnlyWithEntityExpression("Joachim", "Arrasz"); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(secondUser)); - } - - @Test // DATAJPA-606 - public void findByEmptyCollectionOfStrings() throws Exception { - - flushTestUsers(); - - List users = repository.findByAttributesIn(new HashSet()); - assertThat(users, hasSize(0)); - } - - @Test // DATAJPA-606 - public void findByEmptyCollectionOfIntegers() throws Exception { - - flushTestUsers(); - - List users = repository.findByAgeIn(Arrays. asList()); - assertThat(users, hasSize(0)); - } - - @Test // DATAJPA-606 - public void findByEmptyArrayOfIntegers() throws Exception { - - flushTestUsers(); - - List users = repository.queryByAgeIn(new Integer[0]); - assertThat(users, hasSize(0)); - } - - @Test // DATAJPA-606 - public void findByAgeWithEmptyArrayOfIntegersOrFirstName() { - - flushTestUsers(); - - List users = repository.queryByAgeInOrFirstname(new Integer[0], secondUser.getFirstname()); - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(secondUser)); - } - - @Test // DATAJPA-677 - public void shouldSupportJava8StreamsForRepositoryFinderMethods() { - - flushTestUsers(); - - Stream stream = repository.findAllByCustomQueryAndStream(); - - final List users = new ArrayList(); - - try { - - stream.forEach(new Consumer() { - - @Override - public void accept(User user) { - users.add(user); - } - }); - - } finally { - stream.close(); - } - - assertThat(users, hasSize(4)); - } - - @Test // DATAJPA-677 - public void shouldSupportJava8StreamsForRepositoryDerivedFinderMethods() { - - flushTestUsers(); - - Stream stream = repository.readAllByFirstnameNotNull(); - - final List users = new ArrayList(); - - try { - - stream.forEach(new Consumer() { - - @Override - public void accept(User user) { - users.add(user); - } - }); - - } finally { - stream.close(); - } - - assertThat(users, hasSize(4)); - } - - @Test // DATAJPA-677 - public void supportsJava8StreamForPageableMethod() { - - flushTestUsers(); - - Stream stream = repository.streamAllPaged(new PageRequest(0, 2)); - - final List users = new ArrayList(); - - try { - - stream.forEach(new Consumer() { - - @Override - public void accept(User user) { - users.add(user); - } - }); - - } finally { - stream.close(); - } - - assertThat(users, hasSize(2)); - } - - @Test // DATAJPA-218 - public void findAllByExample() { - - flushTestUsers(); - - User prototype = new User(); - prototype.setAge(28); - prototype.setCreatedAt(null); - - List users = repository.findAll(of(prototype)); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(firstUser)); - } - - @Test // DATAJPA-218 - public void findAllByExampleWithEmptyProbe() { - - flushTestUsers(); - - User prototype = new User(); - prototype.setCreatedAt(null); - - List users = repository - .findAll(of(prototype, ExampleMatcher.matching().withIgnorePaths("age", "createdAt", "active"))); - - assertThat(users, hasSize(4)); - } - - @Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218 - public void findAllByNullExample() { - repository.findAll((Example) null); - } - - @Test // DATAJPA-218 - public void findAllByExampleWithExcludedAttributes() { - - flushTestUsers(); - - User prototype = new User(); - prototype.setAge(28); - - Example example = Example.of(prototype, matching().withIgnorePaths("createdAt")); - List users = repository.findAll(example); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(firstUser)); - } - - @Test // DATAJPA-218 - public void findAllByExampleWithAssociation() { - - flushTestUsers(); - - firstUser.setManager(secondUser); - thirdUser.setManager(firstUser); - repository.save(Arrays.asList(firstUser, thirdUser)); - - User manager = new User(); - manager.setLastname("Arrasz"); - manager.setAge(secondUser.getAge()); - manager.setCreatedAt(null); - - User prototype = new User(); - prototype.setCreatedAt(null); - prototype.setManager(manager); - - Example example = Example.of(prototype, matching().withIgnorePaths("age")); - List users = repository.findAll(example); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(firstUser)); - } - - @Test // DATAJPA-218 - public void findAllByExampleWithEmbedded() { - - flushTestUsers(); - - firstUser.setAddress(new Address("germany", "dresden", "", "")); - repository.save(firstUser); - - User prototype = new User(); - prototype.setCreatedAt(null); - prototype.setAddress(new Address("germany", null, null, null)); - - Example example = Example.of(prototype, matching().withIgnorePaths("age")); - List users = repository.findAll(example); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(firstUser)); - } - - @Test // DATAJPA-218 - public void findAllByExampleWithStartingStringMatcher() { - - flushTestUsers(); - - User prototype = new User(); - prototype.setFirstname("Ol"); - - Example example = Example.of(prototype, - matching().withStringMatcher(StringMatcher.STARTING).withIgnorePaths("age", "createdAt")); - List users = repository.findAll(example); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(firstUser)); - } - - @Test // DATAJPA-218 - public void findAllByExampleWithEndingStringMatcher() { - - flushTestUsers(); - - User prototype = new User(); - prototype.setFirstname("ver"); - - Example example = Example.of(prototype, - matching().withStringMatcher(StringMatcher.ENDING).withIgnorePaths("age", "createdAt")); - List users = repository.findAll(example); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(firstUser)); - } - - @Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218 - public void findAllByExampleWithRegexStringMatcher() { - - flushTestUsers(); - - User prototype = new User(); - prototype.setFirstname("^Oliver$"); - - Example example = Example.of(prototype, matching().withStringMatcher(StringMatcher.REGEX)); - repository.findAll(example); - } - - @Test // DATAJPA-218 - public void findAllByExampleWithIgnoreCase() { - - flushTestUsers(); - - User prototype = new User(); - prototype.setFirstname("oLiVer"); - - Example example = Example.of(prototype, matching().withIgnoreCase().withIgnorePaths("age", "createdAt")); - - List users = repository.findAll(example); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(firstUser)); - } - - @Test // DATAJPA-218 - public void findAllByExampleWithStringMatcherAndIgnoreCase() { - - flushTestUsers(); - - User prototype = new User(); - prototype.setFirstname("oLiV"); - - Example example = Example.of(prototype, - matching().withStringMatcher(StringMatcher.STARTING).withIgnoreCase().withIgnorePaths("age", "createdAt")); - - List users = repository.findAll(example); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(firstUser)); - } - - @Test // DATAJPA-218 - public void findAllByExampleWithIncludeNull() { - - // something is wrong with OpenJPA - I do not know what - Assume.assumeThat(PersistenceProvider.fromEntityManager(em), not(equalTo(PersistenceProvider.OPEN_JPA))); - - flushTestUsers(); - - firstUser.setAddress(new Address("andor", "caemlyn", "", "")); - - User fifthUser = new User(); - fifthUser.setEmailAddress("foo@bar.com"); - fifthUser.setActive(firstUser.isActive()); - fifthUser.setAge(firstUser.getAge()); - fifthUser.setFirstname(firstUser.getFirstname()); - fifthUser.setLastname(firstUser.getLastname()); - - repository.save(Arrays.asList(firstUser, fifthUser)); - - User prototype = new User(); - prototype.setFirstname(firstUser.getFirstname()); - - Example example = Example.of(prototype, matching().withIncludeNullValues().withIgnorePaths("id", "binaryData", - "lastname", "emailAddress", "age", "createdAt")); - - List users = repository.findAll(example); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(fifthUser)); - } - - @Test // DATAJPA-218 - public void findAllByExampleWithPropertySpecifier() { - - flushTestUsers(); - - User prototype = new User(); - prototype.setFirstname("oLi"); - - Example example = Example.of(prototype, matching().withIgnoreCase().withIgnorePaths("age", "createdAt") - .withMatcher("firstname", new GenericPropertyMatcher().startsWith())); - - List users = repository.findAll(example); - - assertThat(users, hasSize(1)); - assertThat(users.get(0), is(firstUser)); - } - - @Test // DATAJPA-218 - public void findAllByExampleWithSort() { - - flushTestUsers(); - - User user1 = new User("Oliver", "Srping", "o@s.de"); - user1.setAge(30); - - repository.save(user1); - - User prototype = new User(); - prototype.setFirstname("oLi"); - - Example example = Example.of(prototype, matching().withIgnoreCase().withIgnorePaths("age", "createdAt") - .withStringMatcher(StringMatcher.STARTING).withIgnoreCase()); - - List users = repository.findAll(example, new Sort(DESC, "age")); - - assertThat(users, hasSize(2)); - assertThat(users.get(0), is(user1)); - assertThat(users.get(1), is(firstUser)); - } - - @Test // DATAJPA-218 - public void findAllByExampleWithPageable() { - - flushTestUsers(); - - for (int i = 0; i < 99; i++) { - User user1 = new User("Oliver-" + i, "Srping", "o" + i + "@s.de"); - user1.setAge(30 + i); - - repository.save(user1); - } - - User prototype = new User(); - prototype.setFirstname("oLi"); - - Example example = Example.of(prototype, matching().withIgnoreCase().withIgnorePaths("age", "createdAt") - .withStringMatcher(StringMatcher.STARTING).withIgnoreCase()); - - Page users = repository.findAll(example, new PageRequest(0, 10, new Sort(DESC, "age"))); - - assertThat(users.getSize(), is(10)); - assertThat(users.hasNext(), is(true)); - assertThat(users.getTotalElements(), is(100L)); - } - - @Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218 - public void findAllByExampleShouldNotAllowCycles() { - - flushTestUsers(); - - User user1 = new User(); - user1.setFirstname("user1"); - - user1.setManager(user1); - - Example example = Example.of(user1, matching().withIgnoreCase().withIgnorePaths("age", "createdAt") - .withStringMatcher(StringMatcher.STARTING).withIgnoreCase()); - - repository.findAll(example, new PageRequest(0, 10, new Sort(DESC, "age"))); - } - - @Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218 - public void findAllByExampleShouldNotAllowCyclesOverSeveralInstances() { - - flushTestUsers(); - - User user1 = new User(); - user1.setFirstname("user1"); - - User user2 = new User(); - user2.setFirstname("user2"); - - user1.setManager(user2); - user2.setManager(user1); - - Example example = Example.of(user1, matching().withIgnoreCase().withIgnorePaths("age", "createdAt") - .withStringMatcher(StringMatcher.STARTING).withIgnoreCase()); - - repository.findAll(example, new PageRequest(0, 10, new Sort(DESC, "age"))); - } - - @Test // DATAJPA-218 - public void findOneByExampleWithExcludedAttributes() { - - flushTestUsers(); - - User prototype = new User(); - prototype.setAge(28); - - Example example = Example.of(prototype, matching().withIgnorePaths("createdAt")); - User users = repository.findOne(example); - - assertThat(users, is(firstUser)); - } - - @Test // DATAJPA-218 - public void countByExampleWithExcludedAttributes() { - - flushTestUsers(); - - User prototype = new User(); - prototype.setAge(28); - - Example example = Example.of(prototype, matching().withIgnorePaths("createdAt")); - long count = repository.count(example); - - assertThat(count, is(1L)); - } - - @Test // DATAJPA-218 - public void existsByExampleWithExcludedAttributes() { - - flushTestUsers(); - - User prototype = new User(); - prototype.setAge(28); - - Example example = Example.of(prototype, matching().withIgnorePaths("createdAt")); - boolean exists = repository.exists(example); - - assertThat(exists, is(true)); - } - - @Test // DATAJPA-905 - public void excutesPagedSpecificationSettingAnOrder() { - - flushTestUsers(); - - Page result = repository.findAll(where(userHasLastnameLikeWithSort("e")), new PageRequest(0, 1)); - - assertThat(result.getTotalElements(), is(2L)); - assertThat(result.getNumberOfElements(), is(1)); - assertThat(result.getContent().get(0), is(thirdUser)); - } - - @Test // DATAJPA-1172 - public void queryProvidesCorrectNumberOfParametersForNativeQuery() { - - Query query = em.createNativeQuery("select 1 from User where firstname=? and lastname=?"); - assertThat(query.getParameters(), hasSize(2)); - } - - @Test // DATAJPA-1179 - public void duplicateSpelsWorkAsIntended() { - - flushTestUsers(); - - List users = repository.findUsersByDuplicateSpel("Oliver"); - - assertThat(users, hasSize(1)); - } - - @Test // DATAJPA-980 - public void supportsProjectionsWithNativeQueries() { - - Assume.assumeTrue(Version.getVersionString().startsWith("5.2")); - - flushTestUsers(); - - User user = repository.findAll().get(0); - - NameOnly result = repository.findByNativeQuery(user.getId()); - - assertThat(result.getFirstname(), is(user.getFirstname())); - assertThat(result.getLastname(), is(user.getLastname())); - } - - private Page executeSpecWithSort(Sort sort) { - - flushTestUsers(); - - Specification spec = where(userHasFirstname("Oliver")).or(userHasLastname("Matthews")); - - Page result = repository.findAll(spec, new PageRequest(0, 1, sort)); - assertThat(result.getTotalElements(), is(2L)); - return result; - } -} +/* + * Copyright 2008-2017 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.repository; + +import static org.hamcrest.Matchers.*; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.*; +import static org.springframework.data.domain.Example.*; +import static org.springframework.data.domain.ExampleMatcher.*; +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; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import org.hamcrest.Matchers; +import org.hibernate.Version; +import org.junit.Assume; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.dao.InvalidDataAccessApiUsageException; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.ExampleMatcher; +import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatcher; +import org.springframework.data.domain.ExampleMatcher.StringMatcher; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +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.Specification; +import org.springframework.data.jpa.domain.sample.Address; +import org.springframework.data.jpa.domain.sample.Role; +import org.springframework.data.jpa.domain.sample.SpecialUser; +import org.springframework.data.jpa.domain.sample.User; +import org.springframework.data.jpa.provider.PersistenceProvider; +import org.springframework.data.jpa.repository.sample.SampleEvaluationContextExtension.SampleSecurityContextHolder; +import org.springframework.data.jpa.repository.sample.UserRepository; +import org.springframework.data.jpa.repository.sample.UserRepository.NameOnly; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; + +import com.google.common.base.Optional; + +/** + * Base integration test class for {@code UserRepository}. Loads a basic (non-namespace) Spring configuration file as + * well as Hibernate configuration to execute tests. + *

+ * To test further persistence providers subclass this class and provide a custom provider configuration. + * + * @author Oliver Gierke + * @author Kevin Raymond + * @author Thomas Darimont + * @author Mark Paluch + * @author Jens Schauder + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:application-context.xml") +@Transactional +public class UserRepositoryTests { + + @PersistenceContext EntityManager em; + + // CUT + @Autowired UserRepository repository; + + // Test fixture + User firstUser, secondUser, thirdUser, fourthUser; + Integer id; + Role adminRole; + + @Before + public void setUp() throws Exception { + + firstUser = new User("Oliver", "Gierke", "gierke@synyx.de"); + firstUser.setAge(28); + secondUser = new User("Joachim", "Arrasz", "arrasz@synyx.de"); + secondUser.setAge(35); + Thread.sleep(10); + thirdUser = new User("Dave", "Matthews", "no@email.com"); + thirdUser.setAge(43); + fourthUser = new User("kevin", "raymond", "no@gmail.com"); + fourthUser.setAge(31); + adminRole = new Role("admin"); + + SampleSecurityContextHolder.clear(); + } + + @Test + public void testCreation() { + + Query countQuery = em.createQuery("select count(u) from User u"); + Long before = (Long) countQuery.getSingleResult(); + + flushTestUsers(); + + assertThat((Long) countQuery.getSingleResult(), is(before + 4)); + } + + @Test + public void testRead() throws Exception { + + flushTestUsers(); + + User foundPerson = repository.findOne(id); + assertThat(firstUser.getFirstname(), is(foundPerson.getFirstname())); + } + + @Test + public void findsAllByGivenIds() { + + flushTestUsers(); + + Iterable result = repository.findAll(Arrays.asList(firstUser.getId(), secondUser.getId())); + assertThat(result, hasItems(firstUser, secondUser)); + } + + @Test + public void testReadByIdReturnsNullForNotFoundEntities() { + + flushTestUsers(); + + assertThat(repository.findOne(id * 27), is(nullValue())); + } + + @Test + public void savesCollectionCorrectly() throws Exception { + + List result = repository.save(Arrays.asList(firstUser, secondUser, thirdUser)); + assertThat(result, is(notNullValue())); + assertThat(result.size(), is(3)); + assertThat(result, hasItems(firstUser, secondUser, thirdUser)); + } + + @Test + public void savingNullCollectionIsNoOp() throws Exception { + + List result = repository.save((Collection) null); + assertThat(result, is(notNullValue())); + assertThat(result.isEmpty(), is(true)); + } + + @Test + public void savingEmptyCollectionIsNoOp() throws Exception { + + List result = repository.save(new ArrayList()); + assertThat(result, is(notNullValue())); + assertThat(result.isEmpty(), is(true)); + } + + @Test + public void testUpdate() { + + flushTestUsers(); + + User foundPerson = repository.findOne(id); + foundPerson.setLastname("Schlicht"); + + User updatedPerson = repository.findOne(id); + assertThat(updatedPerson.getFirstname(), is(foundPerson.getFirstname())); + } + + @Test + public void existReturnsWhetherAnEntityCanBeLoaded() throws Exception { + + flushTestUsers(); + assertThat(repository.exists(id), is(true)); + assertThat(repository.exists(id * 27), is(false)); + } + + @Test + public void deletesAUserById() { + + flushTestUsers(); + + repository.delete(firstUser.getId()); + assertThat(repository.exists(id), is(false)); + assertThat(repository.findOne(id), is(nullValue())); + } + + @Test + public void testDelete() { + + flushTestUsers(); + + repository.delete(firstUser); + assertThat(repository.exists(id), is(false)); + assertThat(repository.findOne(id), is(nullValue())); + } + + @Test + public void returnsAllSortedCorrectly() throws Exception { + + flushTestUsers(); + List result = repository.findAll(new Sort(ASC, "lastname")); + assertThat(result, is(notNullValue())); + assertThat(result.size(), is(4)); + assertThat(result.get(0), is(secondUser)); + assertThat(result.get(1), is(firstUser)); + assertThat(result.get(2), is(thirdUser)); + assertThat(result.get(3), is(fourthUser)); + } + + @Test // DATAJPA-296 + public void returnsAllIgnoreCaseSortedCorrectly() throws Exception { + + flushTestUsers(); + + Order order = new Order(ASC, "firstname").ignoreCase(); + List result = repository.findAll(new Sort(order)); + + assertThat(result, is(notNullValue())); + assertThat(result.size(), is(4)); + assertThat(result.get(0), is(thirdUser)); + assertThat(result.get(1), is(secondUser)); + assertThat(result.get(2), is(fourthUser)); + assertThat(result.get(3), is(firstUser)); + } + + @Test + public void deleteColletionOfEntities() { + + flushTestUsers(); + + long before = repository.count(); + + repository.delete(Arrays.asList(firstUser, secondUser)); + assertThat(repository.exists(firstUser.getId()), is(false)); + assertThat(repository.exists(secondUser.getId()), is(false)); + assertThat(repository.count(), is(before - 2)); + } + + @Test + public void batchDeleteColletionOfEntities() { + + flushTestUsers(); + + long before = repository.count(); + + repository.deleteInBatch(Arrays.asList(firstUser, secondUser)); + assertThat(repository.exists(firstUser.getId()), is(false)); + assertThat(repository.exists(secondUser.getId()), is(false)); + assertThat(repository.count(), is(before - 2)); + } + + @Test + public void deleteEmptyCollectionDoesNotDeleteAnything() { + + assertDeleteCallDoesNotDeleteAnything(new ArrayList()); + } + + @Test + public void executesManipulatingQuery() throws Exception { + + flushTestUsers(); + repository.renameAllUsersTo("newLastname"); + + long expected = repository.count(); + assertThat(repository.findByLastname("newLastname").size(), is(Long.valueOf(expected).intValue())); + } + + @Test + public void testFinderInvocationWithNullParameter() { + + flushTestUsers(); + + repository.findByLastname((String) null); + } + + @Test + public void testFindByLastname() throws Exception { + + flushTestUsers(); + + List byName = repository.findByLastname("Gierke"); + + assertThat(byName.size(), is(1)); + assertThat(byName.get(0), is(firstUser)); + } + + /** + * Tests, that searching by the email address of the reference user returns exactly that instance. + * + * @throws Exception + */ + @Test + public void testFindByEmailAddress() throws Exception { + + flushTestUsers(); + + User byName = repository.findByEmailAddress("gierke@synyx.de"); + + assertThat(byName, is(notNullValue())); + assertThat(byName, is(firstUser)); + } + + /** + * Tests reading all users. + */ + @Test + public void testReadAll() { + + flushTestUsers(); + + assertThat(repository.count(), is(4L)); + assertThat(repository.findAll(), hasItems(firstUser, secondUser, thirdUser, fourthUser)); + } + + /** + * Tests that all users get deleted by triggering {@link UserRepository#deleteAll()}. + * + * @throws Exception + */ + @Test + public void deleteAll() throws Exception { + + flushTestUsers(); + + repository.deleteAll(); + + assertThat(repository.count(), is(0L)); + } + + @Test // DATAJPA-137 + public void deleteAllInBatch() { + + flushTestUsers(); + + repository.deleteAllInBatch(); + + assertThat(repository.count(), is(0L)); + } + + /** + * Tests cascading persistence. + */ + @Test + public void testCascadesPersisting() { + + // Create link prior to persisting + firstUser.addColleague(secondUser); + + // Persist + flushTestUsers(); + + // Fetches first user from database + User firstReferenceUser = repository.findOne(firstUser.getId()); + assertThat(firstReferenceUser, is(firstUser)); + + // Fetch colleagues and assert link + Set colleagues = firstReferenceUser.getColleagues(); + assertThat(colleagues.size(), is(1)); + assertThat(colleagues.contains(secondUser), is(true)); + } + + /** + * Tests, that persisting a relationsship without cascade attributes throws a {@code DataAccessException}. + */ + @Test(expected = DataAccessException.class) + public void testPreventsCascadingRolePersisting() { + + firstUser.addRole(new Role("USER")); + + flushTestUsers(); + } + + /** + * Tests cascading on {@literal merge} operation. + */ + @Test + public void testMergingCascadesCollegueas() { + + firstUser.addColleague(secondUser); + flushTestUsers(); + + firstUser.addColleague(new User("Florian", "Hopf", "hopf@synyx.de")); + firstUser = repository.save(firstUser); + + User reference = repository.findOne(firstUser.getId()); + Set colleagues = reference.getColleagues(); + + assertThat(colleagues, is(notNullValue())); + assertThat(colleagues.size(), is(2)); + } + + @Test + public void testCountsCorrectly() { + + long count = repository.count(); + + User user = new User(); + user.setEmailAddress("gierke@synyx.de"); + repository.save(user); + + assertThat(repository.count() == count + 1, is(true)); + } + + @Test + public void testInvocationOfCustomImplementation() { + + repository.someCustomMethod(new User()); + } + + @Test + public void testOverwritingFinder() { + + repository.findByOverrridingMethod(); + } + + @Test + public void testUsesQueryAnnotation() { + + assertThat(repository.findByAnnotatedQuery("gierke@synyx.de"), is(nullValue())); + } + + @Test + public void testExecutionOfProjectingMethod() { + + flushTestUsers(); + assertThat(repository.countWithFirstname("Oliver").longValue(), is(1L)); + } + + @Test + public void executesSpecificationCorrectly() { + + flushTestUsers(); + assertThat(repository.findAll(where(userHasFirstname("Oliver"))).size(), is(1)); + } + + @Test + public void executesSingleEntitySpecificationCorrectly() throws Exception { + + flushTestUsers(); + assertThat(repository.findOne(userHasFirstname("Oliver")), is(firstUser)); + } + + @Test + public void returnsNullIfNoEntityFoundForSingleEntitySpecification() throws Exception { + + flushTestUsers(); + assertThat(repository.findOne(userHasLastname("Beauford")), is(nullValue())); + } + + @Test(expected = IncorrectResultSizeDataAccessException.class) + public void throwsExceptionForUnderSpecifiedSingleEntitySpecification() { + + flushTestUsers(); + repository.findOne(userHasFirstnameLike("e")); + } + + @Test + public void executesCombinedSpecificationsCorrectly() { + + flushTestUsers(); + Specification spec = where(userHasFirstname("Oliver")).or(userHasLastname("Arrasz")); + assertThat(repository.findAll(spec), hasSize(2)); + } + + @Test // DATAJPA-253 + public void executesNegatingSpecificationCorrectly() { + + flushTestUsers(); + Specification spec = not(userHasFirstname("Oliver")).and(userHasLastname("Arrasz")); + List result = repository.findAll(spec); + + assertThat(result, hasSize(1)); + assertThat(result, hasItem(secondUser)); + } + + @Test + public void executesCombinedSpecificationsWithPageableCorrectly() { + + flushTestUsers(); + Specification spec = where(userHasFirstname("Oliver")).or(userHasLastname("Arrasz")); + + Page users = repository.findAll(spec, new PageRequest(0, 1)); + assertThat(users.getSize(), is(1)); + assertThat(users.hasPrevious(), is(false)); + assertThat(users.getTotalElements(), is(2L)); + } + + @Test + public void executesMethodWithAnnotatedNamedParametersCorrectly() throws Exception { + + firstUser = repository.save(firstUser); + secondUser = repository.save(secondUser); + + assertTrue( + repository.findByLastnameOrFirstname("Oliver", "Arrasz").containsAll(Arrays.asList(firstUser, secondUser))); + } + + @Test + public void executesMethodWithNamedParametersCorrectlyOnMethodsWithQueryCreation() throws Exception { + + firstUser = repository.save(firstUser); + secondUser = repository.save(secondUser); + + List result = repository.findByFirstnameOrLastname("Oliver", "Arrasz"); + assertThat(result.size(), is(2)); + assertThat(result, hasItems(firstUser, secondUser)); + } + + @Test + public void executesLikeAndOrderByCorrectly() throws Exception { + + flushTestUsers(); + + List result = repository.findByLastnameLikeOrderByFirstnameDesc("%r%"); + assertThat(result.size(), is(3)); + assertEquals(fourthUser, result.get(0)); + assertEquals(firstUser, result.get(1)); + assertEquals(secondUser, result.get(2)); + } + + @Test + public void executesNotLikeCorrectly() throws Exception { + + flushTestUsers(); + + List result = repository.findByLastnameNotLike("%er%"); + assertThat(result.size(), is(3)); + assertThat(result, hasItems(secondUser, thirdUser, fourthUser)); + } + + @Test + public void executesSimpleNotCorrectly() throws Exception { + + flushTestUsers(); + + List result = repository.findByLastnameNot("Gierke"); + assertThat(result.size(), is(3)); + assertThat(result, hasItems(secondUser, thirdUser, fourthUser)); + } + + @Test + public void returnsSameListIfNoSpecGiven() throws Exception { + + flushTestUsers(); + assertSameElements(repository.findAll(), repository.findAll((Specification) null)); + } + + @Test + public void returnsSameListIfNoSortIsGiven() throws Exception { + + flushTestUsers(); + assertSameElements(repository.findAll((Sort) null), repository.findAll()); + } + + @Test + public void returnsSamePageIfNoSpecGiven() throws Exception { + + Pageable pageable = new PageRequest(0, 1); + + flushTestUsers(); + assertThat(repository.findAll((Specification) null, pageable), is(repository.findAll(pageable))); + } + + @Test + public void returnsAllAsPageIfNoPageableIsGiven() throws Exception { + + flushTestUsers(); + assertThat(repository.findAll((Pageable) null), is((Page) new PageImpl(repository.findAll()))); + } + + @Test + public void removeDetachedObject() throws Exception { + + flushTestUsers(); + + em.detach(firstUser); + repository.delete(firstUser); + + assertThat(repository.count(), is(3L)); + } + + @Test + public void executesPagedSpecificationsCorrectly() throws Exception { + + Page result = executeSpecWithSort(null); + assertThat(result.getContent(), anyOf(hasItem(firstUser), hasItem(thirdUser))); + assertThat(result.getContent(), not(hasItem(secondUser))); + } + + @Test + public void executesPagedSpecificationsWithSortCorrectly() throws Exception { + + Page result = executeSpecWithSort(new Sort(Direction.ASC, "lastname")); + + assertThat(result.getContent(), hasItem(firstUser)); + assertThat(result.getContent(), not(hasItem(secondUser))); + assertThat(result.getContent(), not(hasItem(thirdUser))); + } + + @Test + public void executesPagedSpecificationWithSortCorrectly2() throws Exception { + + Page result = executeSpecWithSort(new Sort(Direction.DESC, "lastname")); + + assertThat(result.getContent(), hasItem(thirdUser)); + assertThat(result.getContent(), not(hasItem(secondUser))); + assertThat(result.getContent(), not(hasItem(firstUser))); + } + + @Test + public void executesQueryMethodWithDeepTraversalCorrectly() throws Exception { + + flushTestUsers(); + + firstUser.setManager(secondUser); + thirdUser.setManager(firstUser); + repository.save(Arrays.asList(firstUser, thirdUser)); + + List result = repository.findByManagerLastname("Arrasz"); + + assertThat(result.size(), is(1)); + assertThat(result, hasItem(firstUser)); + + result = repository.findByManagerLastname("Gierke"); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(thirdUser)); + } + + @Test + public void executesFindByColleaguesLastnameCorrectly() throws Exception { + + flushTestUsers(); + + firstUser.addColleague(secondUser); + thirdUser.addColleague(firstUser); + repository.save(Arrays.asList(firstUser, thirdUser)); + + List result = repository.findByColleaguesLastname(secondUser.getLastname()); + + assertThat(result.size(), is(1)); + assertThat(result, hasItem(firstUser)); + + result = repository.findByColleaguesLastname("Gierke"); + assertThat(result.size(), is(2)); + assertThat(result, hasItems(thirdUser, secondUser)); + } + + @Test + public void executesFindByNotNullLastnameCorrectly() throws Exception { + + flushTestUsers(); + List result = repository.findByLastnameNotNull(); + + assertThat(result.size(), is(4)); + assertThat(result, hasItems(firstUser, secondUser, thirdUser, fourthUser)); + } + + @Test + public void executesFindByNullLastnameCorrectly() throws Exception { + + flushTestUsers(); + User forthUser = repository.save(new User("Foo", null, "email@address.com")); + + List result = repository.findByLastnameNull(); + + assertThat(result.size(), is(1)); + assertThat(result, hasItems(forthUser)); + } + + @Test + public void findsSortedByLastname() throws Exception { + + flushTestUsers(); + + List result = repository.findByEmailAddressLike("%@%", new Sort(Direction.ASC, "lastname")); + + assertThat(result.size(), is(4)); + assertThat(result.get(0), is(secondUser)); + assertThat(result.get(1), is(firstUser)); + assertThat(result.get(2), is(thirdUser)); + assertThat(result.get(3), is(fourthUser)); + } + + @Test + public void findsUsersBySpringDataNamedQuery() { + + flushTestUsers(); + + List result = repository.findBySpringDataNamedQuery("Gierke"); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(firstUser)); + } + + @Test // DATADOC-86 + public void readsPageWithGroupByClauseCorrectly() { + + flushTestUsers(); + + Page result = repository.findByLastnameGrouped(new PageRequest(0, 10)); + assertThat(result.getTotalPages(), is(1)); + } + + @Test + public void executesLessThatOrEqualQueriesCorrectly() { + + flushTestUsers(); + + List result = repository.findByAgeLessThanEqual(35); + assertThat(result.size(), is(3)); + assertThat(result, hasItems(firstUser, secondUser, fourthUser)); + } + + @Test + public void executesGreaterThatOrEqualQueriesCorrectly() { + + flushTestUsers(); + + List result = repository.findByAgeGreaterThanEqual(35); + assertThat(result.size(), is(2)); + assertThat(result, hasItems(secondUser, thirdUser)); + } + + @Test // DATAJPA-117 + public void executesNativeQueryCorrectly() { + + flushTestUsers(); + + List result = repository.findNativeByLastname("Matthews"); + + assertThat(result, hasItem(thirdUser)); + assertThat(result.size(), is(1)); + } + + @Test // DATAJPA-132 + public void executesFinderWithTrueKeywordCorrectly() { + + flushTestUsers(); + firstUser.setActive(false); + repository.save(firstUser); + + List result = repository.findByActiveTrue(); + assertThat(result.size(), is(3)); + assertThat(result, hasItems(secondUser, thirdUser, fourthUser)); + } + + @Test // DATAJPA-132 + public void executesFinderWithFalseKeywordCorrectly() { + + flushTestUsers(); + firstUser.setActive(false); + repository.save(firstUser); + + List result = repository.findByActiveFalse(); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(firstUser)); + } + + /** + * Ignored until the query declaration is supported by OpenJPA. + */ + @Test + @Ignore + public void executesAnnotatedCollectionMethodCorrectly() { + + flushTestUsers(); + firstUser.addColleague(thirdUser); + repository.save(firstUser); + + List result = null; // repository.findColleaguesFor(firstUser); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(thirdUser)); + } + + @Test // DATAJPA-188 + public void executesFinderWithAfterKeywordCorrectly() { + + flushTestUsers(); + + List result = repository.findByCreatedAtAfter(secondUser.getCreatedAt()); + assertThat(result.size(), is(2)); + assertThat(result, hasItems(thirdUser, fourthUser)); + } + + @Test // DATAJPA-188 + public void executesFinderWithBeforeKeywordCorrectly() { + + flushTestUsers(); + + List result = repository.findByCreatedAtBefore(thirdUser.getCreatedAt()); + assertThat(result.size(), is(2)); + assertThat(result, hasItems(firstUser, secondUser)); + } + + @Test // DATAJPA-180 + public void executesFinderWithStartingWithCorrectly() { + + flushTestUsers(); + List result = repository.findByFirstnameStartingWith("Oli"); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(firstUser)); + } + + @Test // DATAJPA-180 + public void executesFinderWithEndingWithCorrectly() { + + flushTestUsers(); + List result = repository.findByFirstnameEndingWith("er"); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(firstUser)); + } + + @Test // DATAJPA-180 + public void executesFinderWithContainingCorrectly() { + + flushTestUsers(); + List result = repository.findByFirstnameContaining("a"); + assertThat(result.size(), is(2)); + assertThat(result, hasItems(secondUser, thirdUser)); + } + + @Test // DATAJPA-201 + public void allowsExecutingPageableMethodWithNullPageable() { + + flushTestUsers(); + + List users = repository.findByFirstname("Oliver", null); + assertThat(users.size(), is(1)); + assertThat(users, hasItem(firstUser)); + + Page page = repository.findByFirstnameIn(null, "Oliver"); + assertThat(page.getNumberOfElements(), is(1)); + assertThat(page.getContent(), hasItem(firstUser)); + + page = repository.findAll((Pageable) null); + assertThat(page.getNumberOfElements(), is(4)); + assertThat(page.getContent(), hasItems(firstUser, secondUser, thirdUser, fourthUser)); + } + + @Test // DATAJPA-207 + public void executesNativeQueryForNonEntitiesCorrectly() { + + flushTestUsers(); + + List result = repository.findOnesByNativeQuery(); + + assertThat(result.size(), is(4)); + assertThat(result, hasItem(1)); + } + + @Test // DATAJPA-232 + public void handlesIterableOfIdsCorrectly() { + + flushTestUsers(); + + Set set = new HashSet(); + set.add(firstUser.getId()); + set.add(secondUser.getId()); + + Iterable result = repository.findAll(set); + + assertThat(result, is(Matchers. iterableWithSize(2))); + assertThat(result, hasItems(firstUser, secondUser)); + } + + protected void flushTestUsers() { + + em.persist(adminRole); + + firstUser = repository.save(firstUser); + secondUser = repository.save(secondUser); + thirdUser = repository.save(thirdUser); + fourthUser = repository.save(fourthUser); + + repository.flush(); + + id = firstUser.getId(); + + assertThat(id, is(notNullValue())); + assertThat(secondUser.getId(), is(notNullValue())); + assertThat(thirdUser.getId(), is(notNullValue())); + assertThat(fourthUser.getId(), is(notNullValue())); + + assertThat(repository.exists(id), is(true)); + assertThat(repository.exists(secondUser.getId()), is(true)); + assertThat(repository.exists(thirdUser.getId()), is(true)); + assertThat(repository.exists(fourthUser.getId()), is(true)); + } + + private static void assertSameElements(Collection first, Collection second) { + + for (T element : first) { + assertThat(element, isIn(second)); + } + + for (T element : second) { + assertThat(element, isIn(first)); + } + } + + private void assertDeleteCallDoesNotDeleteAnything(List collection) { + + flushTestUsers(); + long count = repository.count(); + + repository.delete(collection); + assertThat(repository.count(), is(count)); + } + + @Test + public void ordersByReferencedEntityCorrectly() { + + flushTestUsers(); + firstUser.setManager(thirdUser); + repository.save(firstUser); + + Page all = repository.findAll(new PageRequest(0, 10, new Sort("manager.id"))); + + assertThat(all.getContent().isEmpty(), is(false)); + } + + @Test // DATAJPA-252 + public void bindsSortingToOuterJoinCorrectly() { + + flushTestUsers(); + + // Managers not set, make sure adding the sort does not rule out those Users + Page result = repository.findAllPaged(new PageRequest(0, 10, new Sort("manager.lastname"))); + assertThat(result.getContent(), hasSize((int) repository.count())); + } + + @Test // DATAJPA-277 + public void doesNotDropNullValuesOnPagedSpecificationExecution() { + + flushTestUsers(); + + Page page = repository.findAll(new Specification() { + public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) { + return cb.equal(root.get("lastname"), "Gierke"); + } + }, new PageRequest(0, 20, new Sort("manager.lastname"))); + + assertThat(page.getNumberOfElements(), is(1)); + assertThat(page, hasItem(firstUser)); + } + + @Test // DATAJPA-346 + public void shouldGenerateLeftOuterJoinInfindAllWithPaginationAndSortOnNestedPropertyPath() { + + firstUser.setManager(null); + secondUser.setManager(null); + thirdUser.setManager(firstUser); // manager Oliver + fourthUser.setManager(secondUser); // manager Joachim + + flushTestUsers(); + + Page pages = repository.findAll(new PageRequest(0, 4, new Sort(Sort.Direction.ASC, "manager.firstname"))); + assertThat(pages.getSize(), is(4)); + assertThat(pages.getContent().get(0).getManager(), is(nullValue())); + assertThat(pages.getContent().get(1).getManager(), is(nullValue())); + assertThat(pages.getContent().get(2).getManager().getFirstname(), is("Joachim")); + assertThat(pages.getContent().get(3).getManager().getFirstname(), is("Oliver")); + assertThat(pages.getTotalElements(), is(4L)); + } + + @Test // DATAJPA-292 + public void executesManualQueryWithPositionLikeExpressionCorrectly() { + + flushTestUsers(); + + List result = repository.findByFirstnameLike("Da"); + + assertThat(result, hasSize(1)); + assertThat(result, hasItem(thirdUser)); + } + + @Test // DATAJPA-292 + public void executesManualQueryWithNamedLikeExpressionCorrectly() { + + flushTestUsers(); + + List result = repository.findByFirstnameLikeNamed("Da"); + + assertThat(result, hasSize(1)); + assertThat(result, hasItem(thirdUser)); + } + + @Test // DATAJPA-231 + public void executesDerivedCountQueryToLong() { + + flushTestUsers(); + + assertThat(repository.countByLastname("Matthews"), is(1L)); + } + + @Test // DATAJPA-231 + public void executesDerivedCountQueryToInt() { + + flushTestUsers(); + + assertThat(repository.countUsersByFirstname("Dave"), is(1)); + } + + @Test // DATAJPA-231 + public void executesDerivedExistsQuery() { + + flushTestUsers(); + + assertThat(repository.existsByLastname("Matthews"), is(true)); + assertThat(repository.existsByLastname("Hans Peter"), is(false)); + } + + @Test // DATAJPA-332 + public void findAllReturnsEmptyIterableIfNoIdsGiven() { + + assertThat(repository.findAll(Collections. emptySet()), is(emptyIterable())); + assertThat(repository.findAll((Iterable) null), is(emptyIterable())); + } + + @Test // DATAJPA-391 + public void executesManuallyDefinedQueryWithFieldProjection() { + + flushTestUsers(); + List lastname = repository.findFirstnamesByLastname("Matthews"); + + assertThat(lastname, hasSize(1)); + assertThat(lastname, hasItem("Dave")); + } + + @Test // DATAJPA-83 + public void looksUpEntityReference() { + + flushTestUsers(); + + User result = repository.getOne(firstUser.getId()); + assertThat(result, is(firstUser)); + } + + @Test // DATAJPA-415 + public void invokesQueryWithVarargsParametersCorrectly() { + + flushTestUsers(); + + Collection result = repository.findByIdIn(firstUser.getId(), secondUser.getId()); + + assertThat(result, hasSize(2)); + assertThat(result, hasItems(firstUser, secondUser)); + } + + @Test // DATAJPA-415 + public void shouldSupportModifyingQueryWithVarArgs() { + + flushTestUsers(); + + repository.updateUserActiveState(false, firstUser.getId(), secondUser.getId(), thirdUser.getId(), + fourthUser.getId()); + + long expectedCount = repository.count(); + assertThat(repository.findByActiveFalse().size(), is((int) expectedCount)); + assertThat(repository.findByActiveTrue().size(), is(0)); + } + + @Test // DATAJPA-405 + public void executesFinderWithOrderClauseOnly() { + + flushTestUsers(); + + List result = repository.findAllByOrderByLastnameAsc(); + + assertThat(result, hasSize(4)); + assertThat(result, contains(secondUser, firstUser, thirdUser, fourthUser)); + } + + @Test // DATAJPA-427 + public void sortByAssociationPropertyShouldUseLeftOuterJoin() { + + secondUser.getColleagues().add(firstUser); + fourthUser.getColleagues().add(thirdUser); + flushTestUsers(); + + List result = repository.findAll(new Sort(Sort.Direction.ASC, "colleagues.id")); + + assertThat(result, hasSize(4)); + } + + @Test // DATAJPA-427 + public void sortByAssociationPropertyInPageableShouldUseLeftOuterJoin() { + + secondUser.getColleagues().add(firstUser); + fourthUser.getColleagues().add(thirdUser); + flushTestUsers(); + + Page page = repository.findAll(new PageRequest(0, 10, new Sort(Sort.Direction.ASC, "colleagues.id"))); + + assertThat(page.getContent(), hasSize(4)); + } + + @Test // DATAJPA-427 + public void sortByEmbeddedProperty() { + + thirdUser.setAddress(new Address("Germany", "Saarbrücken", "HaveItYourWay", "123")); + flushTestUsers(); + + Page page = repository.findAll(new PageRequest(0, 10, new Sort(Sort.Direction.ASC, "address.streetName"))); + + assertThat(page.getContent(), hasSize(4)); + assertThat(page.getContent().get(3), is(thirdUser)); + } + + @Test // DATAJPA-454 + public void findsUserByBinaryDataReference() throws Exception { + + byte[] data = "Woho!!".getBytes("UTF-8"); + firstUser.setBinaryData(data); + + flushTestUsers(); + + List result = repository.findByBinaryData(data); + assertThat(result, hasSize(1)); + assertThat(result, hasItem(firstUser)); + assertThat(result.get(0).getBinaryData(), is(data)); + } + + @Test // DATAJPA-461 + public void customFindByQueryWithPositionalVarargsParameters() { + + flushTestUsers(); + + Collection result = repository.findByIdsCustomWithPositionalVarArgs(firstUser.getId(), secondUser.getId()); + + assertThat(result, hasSize(2)); + assertThat(result, hasItems(firstUser, secondUser)); + } + + @Test // DATAJPA-461 + public void customFindByQueryWithNamedVarargsParameters() { + + flushTestUsers(); + + Collection result = repository.findByIdsCustomWithNamedVarArgs(firstUser.getId(), secondUser.getId()); + + assertThat(result, hasSize(2)); + assertThat(result, hasItems(firstUser, secondUser)); + } + + @Test // DATAJPA-464 + public void saveAndFlushShouldSupportReturningSubTypesOfRepositoryEntity() { + + repository.deleteAll(); + SpecialUser user = new SpecialUser(); + user.setFirstname("Thomas"); + user.setEmailAddress("thomas@example.org"); + + SpecialUser savedUser = repository.saveAndFlush(user); + + assertThat(user.getFirstname(), is(savedUser.getFirstname())); + assertThat(user.getEmailAddress(), is(savedUser.getEmailAddress())); + } + + @Test // DATAJPA-218 + public void findAllByUntypedExampleShouldReturnSubTypesOfRepositoryEntity() { + + flushTestUsers(); + + SpecialUser user = new SpecialUser(); + user.setFirstname("Thomas"); + user.setEmailAddress("thomas@example.org"); + + repository.saveAndFlush(user); + + List result = repository + .findAll(Example.of(new User(), ExampleMatcher.matching().withIgnorePaths("age", "createdAt", "dateOfBirth"))); + + assertThat(result, hasSize(5)); + } + + @Test // DATAJPA-218 + public void findAllByTypedUserExampleShouldReturnSubTypesOfRepositoryEntity() { + + flushTestUsers(); + + SpecialUser user = new SpecialUser(); + user.setFirstname("Thomas"); + user.setEmailAddress("thomas@example.org"); + + repository.saveAndFlush(user); + + Example example = Example.of(new User(), matching().withIgnorePaths("age", "createdAt", "dateOfBirth")); + List result = repository.findAll(example); + + assertThat(result, hasSize(5)); + } + + @Test // DATAJPA-218 + public void findAllByTypedSpecialUserExampleShouldReturnSubTypesOfRepositoryEntity() { + + flushTestUsers(); + + SpecialUser user = new SpecialUser(); + user.setFirstname("Thomas"); + user.setEmailAddress("thomas@example.org"); + + repository.saveAndFlush(user); + + Example example = Example.of(new SpecialUser(), + matching().withIgnorePaths("age", "createdAt", "dateOfBirth")); + List result = repository.findAll(example); + + assertThat(result, hasSize(1)); + } + + @Test // DATAJPA-491 + public void sortByNestedAssociationPropertyWithSortInPageable() { + + firstUser.setManager(thirdUser); + thirdUser.setManager(fourthUser); + + flushTestUsers(); + + Page page = repository.findAll(new PageRequest(0, 10, // + new Sort(Sort.Direction.ASC, "manager.manager.firstname"))); + + assertThat(page.getContent(), hasSize(4)); + assertThat(page.getContent().get(3), is(firstUser)); + } + + @Test // DATAJPA-510 + public void sortByNestedAssociationPropertyWithSortOrderIgnoreCaseInPageable() { + + firstUser.setManager(thirdUser); + thirdUser.setManager(fourthUser); + + flushTestUsers(); + + Page page = repository.findAll(new PageRequest(0, 10, // + new Sort(new Sort.Order(Direction.ASC, "manager.manager.firstname").ignoreCase()))); + + assertThat(page.getContent(), hasSize(4)); + assertThat(page.getContent().get(3), is(firstUser)); + } + + @Test // DATAJPA-496 + public void findByElementCollectionAttribute() { + + firstUser.getAttributes().add("cool"); + secondUser.getAttributes().add("hip"); + thirdUser.getAttributes().add("rockstar"); + + flushTestUsers(); + + List result = repository.findByAttributesIn(new HashSet(Arrays.asList("cool", "hip"))); + + assertThat(result, hasSize(2)); + assertThat(result, hasItems(firstUser, secondUser)); + } + + @Test // DATAJPA-460 + public void deleteByShouldReturnListOfDeletedElementsWhenRetunTypeIsCollectionLike() { + + flushTestUsers(); + + List result = repository.deleteByLastname(firstUser.getLastname()); + assertThat(result, hasItem(firstUser)); + assertThat(result, hasSize(1)); + } + + @Test // DATAJPA-460 + public void deleteByShouldRemoveElementsMatchingDerivedQuery() { + + flushTestUsers(); + + repository.deleteByLastname(firstUser.getLastname()); + assertThat(repository.countByLastname(firstUser.getLastname()), is(0L)); + } + + @Test // DATAJPA-460 + public void deleteByShouldReturnNumberOfEntitiesRemovedIfReturnTypeIsLong() { + + flushTestUsers(); + + assertThat(repository.removeByLastname(firstUser.getLastname()), is(1L)); + } + + @Test // DATAJPA-460 + public void deleteByShouldReturnZeroInCaseNoEntityHasBeenRemovedAndReturnTypeIsNumber() { + + flushTestUsers(); + + assertThat(repository.removeByLastname("bubu"), is(0L)); + } + + @Test // DATAJPA-460 + public void deleteByShouldReturnEmptyListInCaseNoEntityHasBeenRemovedAndReturnTypeIsCollectionLike() { + + flushTestUsers(); + + assertThat(repository.deleteByLastname("dorfuaeB"), empty()); + } + + /** + * @see OPENJPA-2484 + */ + @Test // DATAJPA-505 + @Ignore + public void findBinaryDataByIdJpaQl() throws Exception { + + byte[] data = "Woho!!".getBytes("UTF-8"); + firstUser.setBinaryData(data); + + flushTestUsers(); + + byte[] result = null; // repository.findBinaryDataByIdJpaQl(firstUser.getId()); + + assertThat(result.length, is(data.length)); + assertThat(result, is(data)); + } + + @Test // DATAJPA-506 + public void findBinaryDataByIdNative() throws Exception { + + byte[] data = "Woho!!".getBytes("UTF-8"); + firstUser.setBinaryData(data); + + flushTestUsers(); + + byte[] result = repository.findBinaryDataByIdNative(firstUser.getId()); + assertThat(result.length, is(data.length)); + assertThat(result, is(data)); + } + + @Test // DATAJPA-456 + public void findPaginatedExplicitQueryWithCountQueryProjection() { + + firstUser.setFirstname(null); + + flushTestUsers(); + + Page result = repository.findAllByFirstnameLike("", new PageRequest(0, 10)); + + assertThat(result.getContent().size(), is(3)); + } + + @Test // DATAJPA-456 + public void findPaginatedNamedQueryWithCountQueryProjection() { + + flushTestUsers(); + + Page result = repository.findByNamedQueryAndCountProjection("Gierke", new PageRequest(0, 10)); + + assertThat(result.getContent().size(), is(1)); + } + + @Test // DATAJPA-551 + public void findOldestUser() { + + flushTestUsers(); + + User oldest = thirdUser; + + assertThat(repository.findFirstByOrderByAgeDesc(), is(oldest)); + assertThat(repository.findFirst1ByOrderByAgeDesc(), is(oldest)); + } + + @Test // DATAJPA-551 + public void findYoungestUser() { + + flushTestUsers(); + + User youngest = firstUser; + + assertThat(repository.findTopByOrderByAgeAsc(), is(youngest)); + assertThat(repository.findTop1ByOrderByAgeAsc(), is(youngest)); + } + + @Test // DATAJPA-551 + public void find2OldestUsers() { + + flushTestUsers(); + + User oldest1 = thirdUser; + User oldest2 = secondUser; + + assertThat(repository.findFirst2ByOrderByAgeDesc(), hasItems(oldest1, oldest2)); + assertThat(repository.findTop2ByOrderByAgeDesc(), hasItems(oldest1, oldest2)); + } + + @Test // DATAJPA-551 + public void find2YoungestUsers() { + + flushTestUsers(); + + User youngest1 = firstUser; + User youngest2 = fourthUser; + + assertThat(repository.findFirst2UsersBy(new Sort(ASC, "age")), hasItems(youngest1, youngest2)); + assertThat(repository.findTop2UsersBy(new Sort(ASC, "age")), hasItems(youngest1, youngest2)); + } + + @Test // DATAJPA-551 + public void find3YoungestUsersPageableWithPageSize2() { + + flushTestUsers(); + + User youngest1 = firstUser; + User youngest2 = fourthUser; + User youngest3 = secondUser; + + Page firstPage = repository.findFirst3UsersBy(new PageRequest(0, 2, ASC, "age")); + assertThat(firstPage.getContent(), hasItems(youngest1, youngest2)); + + Page secondPage = repository.findFirst3UsersBy(new PageRequest(1, 2, ASC, "age")); + assertThat(secondPage.getContent(), hasItems(youngest3)); + } + + @Test // DATAJPA-551 + public void find2YoungestUsersPageableWithPageSize3() { + + flushTestUsers(); + + User youngest1 = firstUser; + User youngest2 = fourthUser; + User youngest3 = secondUser; + + Page firstPage = repository.findFirst2UsersBy(new PageRequest(0, 3, ASC, "age")); + assertThat(firstPage.getContent(), hasItems(youngest1, youngest2)); + + Page secondPage = repository.findFirst2UsersBy(new PageRequest(1, 3, ASC, "age")); + assertThat(secondPage.getContent(), hasItems(youngest3)); + } + + @Test // DATAJPA-551 + public void find3YoungestUsersPageableWithPageSize2Sliced() { + + flushTestUsers(); + + User youngest1 = firstUser; + User youngest2 = fourthUser; + User youngest3 = secondUser; + + Slice firstPage = repository.findTop3UsersBy(new PageRequest(0, 2, ASC, "age")); + assertThat(firstPage.getContent(), hasItems(youngest1, youngest2)); + + Slice secondPage = repository.findTop3UsersBy(new PageRequest(1, 2, ASC, "age")); + assertThat(secondPage.getContent(), hasItems(youngest3)); + } + + @Test // DATAJPA-551 + public void find2YoungestUsersPageableWithPageSize3Sliced() { + + flushTestUsers(); + + User youngest1 = firstUser; + User youngest2 = fourthUser; + User youngest3 = secondUser; + + Slice firstPage = repository.findTop2UsersBy(new PageRequest(0, 3, ASC, "age")); + assertThat(firstPage.getContent(), hasItems(youngest1, youngest2)); + + Slice secondPage = repository.findTop2UsersBy(new PageRequest(1, 3, ASC, "age")); + assertThat(secondPage.getContent(), hasItems(youngest3)); + } + + @Test // DATAJPA-912 + public void pageableQueryReportsTotalFromResult() { + + flushTestUsers(); + + Page firstPage = repository.findAll(new PageRequest(0, 10)); + assertThat(firstPage.getContent(), hasSize(4)); + assertThat(firstPage.getTotalElements(), is(4L)); + + Page secondPage = repository.findAll(new PageRequest(1, 3)); + assertThat(secondPage.getContent(), hasSize(1)); + assertThat(secondPage.getTotalElements(), is(4L)); + } + + @Test // DATAJPA-912 + public void pageableQueryReportsTotalFromCount() { + + flushTestUsers(); + + Page firstPage = repository.findAll(new PageRequest(0, 4)); + assertThat(firstPage.getContent(), hasSize(4)); + assertThat(firstPage.getTotalElements(), is(4L)); + + Page secondPage = repository.findAll(new PageRequest(10, 10)); + assertThat(secondPage.getContent(), hasSize(0)); + assertThat(secondPage.getTotalElements(), is(4L)); + } + + @Test // DATAJPA-506 + public void invokesQueryWithWrapperType() { + + flushTestUsers(); + + Optional result = repository.findOptionalByEmailAddress("gierke@synyx.de"); + + assertThat(result.isPresent(), is(true)); + assertThat(result.get(), is(firstUser)); + } + + @Test // DATAJPA-564 + public void shouldFindUserByFirstnameAndLastnameWithSpelExpressionInStringBasedQuery() { + + flushTestUsers(); + List users = repository.findByFirstnameAndLastnameWithSpelExpression("Oliver", "ierk"); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(firstUser)); + } + + @Test // DATAJPA-564 + public void shouldFindUserByLastnameWithSpelExpressionInStringBasedQuery() { + + flushTestUsers(); + List users = repository.findByLastnameWithSpelExpression("ierk"); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(firstUser)); + } + + @Test // DATAJPA-564 + public void shouldFindBySpELExpressionWithoutArgumentsWithQuestionmark() { + + flushTestUsers(); + List users = repository.findOliverBySpELExpressionWithoutArgumentsWithQuestionmark(); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(firstUser)); + } + + @Test // DATAJPA-564 + public void shouldFindBySpELExpressionWithoutArgumentsWithColon() { + + flushTestUsers(); + List users = repository.findOliverBySpELExpressionWithoutArgumentsWithColon(); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(firstUser)); + } + + @Test // DATAJPA-564 + public void shouldFindUsersByAgeForSpELExpression() { + + flushTestUsers(); + List users = repository.findUsersByAgeForSpELExpressionByIndexedParameter(35); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(secondUser)); + } + + @Test // DATAJPA-564 + public void shouldfindUsersByFirstnameForSpELExpressionWithParameterNameVariableReference() { + + flushTestUsers(); + List users = repository.findUsersByFirstnameForSpELExpression("Joachim"); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(secondUser)); + } + + @Test // DATAJPA-564 + public void shouldFindCurrentUserWithCustomQueryDependingOnSecurityContext() { + + flushTestUsers(); + + SampleSecurityContextHolder.getCurrent().setPrincipal(secondUser); + List users = repository.findCurrentUserWithCustomQuery(); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(secondUser)); + + SampleSecurityContextHolder.getCurrent().setPrincipal(firstUser); + users = repository.findCurrentUserWithCustomQuery(); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(firstUser)); + } + + @Test // DATAJPA-564 + public void shouldFindByFirstnameAndCurrentUserWithCustomQuery() { + + flushTestUsers(); + + SampleSecurityContextHolder.getCurrent().setPrincipal(secondUser); + List users = repository.findByFirstnameAndCurrentUserWithCustomQuery("Joachim"); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(secondUser)); + } + + @Test // DATAJPA-564 + public void shouldfindUsersByFirstnameForSpELExpressionOnlyWithParameterNameVariableReference() { + + flushTestUsers(); + List users = repository.findUsersByFirstnameForSpELExpressionWithParameterVariableOnly("Joachim"); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(secondUser)); + } + + @Test // DATAJPA-564 + public void shouldfindUsersByFirstnameForSpELExpressionOnlyWithParameterIndexReference() { + + flushTestUsers(); + List users = repository.findUsersByFirstnameForSpELExpressionWithParameterIndexOnly("Joachim"); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(secondUser)); + } + + @Test // DATAJPA-564 + public void shouldFindUsersInNativeQueryWithPagination() { + + flushTestUsers(); + + Page users = repository.findUsersInNativeQueryWithPagination(new PageRequest(0, 2)); + + assertThat(users.getContent(), hasSize(2)); + assertThat(users.getContent().get(0), is(firstUser)); + assertThat(users.getContent().get(1), is(secondUser)); + + users = repository.findUsersInNativeQueryWithPagination(new PageRequest(1, 2)); + + assertThat(users.getContent(), hasSize(2)); + assertThat(users.getContent().get(0), is(thirdUser)); + assertThat(users.getContent().get(1), is(fourthUser)); + } + + @Test // DATAJPA-629 + public void shouldfindUsersBySpELExpressionParametersWithSpelTemplateExpression() { + + flushTestUsers(); + List users = repository + .findUsersByFirstnameForSpELExpressionWithParameterIndexOnlyWithEntityExpression("Joachim", "Arrasz"); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(secondUser)); + } + + @Test // DATAJPA-606 + public void findByEmptyCollectionOfStrings() throws Exception { + + flushTestUsers(); + + List users = repository.findByAttributesIn(new HashSet()); + assertThat(users, hasSize(0)); + } + + @Test // DATAJPA-606 + public void findByEmptyCollectionOfIntegers() throws Exception { + + flushTestUsers(); + + List users = repository.findByAgeIn(Arrays. asList()); + assertThat(users, hasSize(0)); + } + + @Test // DATAJPA-606 + public void findByEmptyArrayOfIntegers() throws Exception { + + flushTestUsers(); + + List users = repository.queryByAgeIn(new Integer[0]); + assertThat(users, hasSize(0)); + } + + @Test // DATAJPA-606 + public void findByAgeWithEmptyArrayOfIntegersOrFirstName() { + + flushTestUsers(); + + List users = repository.queryByAgeInOrFirstname(new Integer[0], secondUser.getFirstname()); + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(secondUser)); + } + + @Test // DATAJPA-677 + public void shouldSupportJava8StreamsForRepositoryFinderMethods() { + + flushTestUsers(); + + Stream stream = repository.findAllByCustomQueryAndStream(); + + final List users = new ArrayList(); + + try { + + stream.forEach(new Consumer() { + + @Override + public void accept(User user) { + users.add(user); + } + }); + + } finally { + stream.close(); + } + + assertThat(users, hasSize(4)); + } + + @Test // DATAJPA-677 + public void shouldSupportJava8StreamsForRepositoryDerivedFinderMethods() { + + flushTestUsers(); + + Stream stream = repository.readAllByFirstnameNotNull(); + + final List users = new ArrayList(); + + try { + + stream.forEach(new Consumer() { + + @Override + public void accept(User user) { + users.add(user); + } + }); + + } finally { + stream.close(); + } + + assertThat(users, hasSize(4)); + } + + @Test // DATAJPA-677 + public void supportsJava8StreamForPageableMethod() { + + flushTestUsers(); + + Stream stream = repository.streamAllPaged(new PageRequest(0, 2)); + + final List users = new ArrayList(); + + try { + + stream.forEach(new Consumer() { + + @Override + public void accept(User user) { + users.add(user); + } + }); + + } finally { + stream.close(); + } + + assertThat(users, hasSize(2)); + } + + @Test // DATAJPA-218 + public void findAllByExample() { + + flushTestUsers(); + + User prototype = new User(); + prototype.setAge(28); + prototype.setCreatedAt(null); + + List users = repository.findAll(of(prototype)); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(firstUser)); + } + + @Test // DATAJPA-218 + public void findAllByExampleWithEmptyProbe() { + + flushTestUsers(); + + User prototype = new User(); + prototype.setCreatedAt(null); + + List users = repository + .findAll(of(prototype, ExampleMatcher.matching().withIgnorePaths("age", "createdAt", "active"))); + + assertThat(users, hasSize(4)); + } + + @Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218 + public void findAllByNullExample() { + repository.findAll((Example) null); + } + + @Test // DATAJPA-218 + public void findAllByExampleWithExcludedAttributes() { + + flushTestUsers(); + + User prototype = new User(); + prototype.setAge(28); + + Example example = Example.of(prototype, matching().withIgnorePaths("createdAt")); + List users = repository.findAll(example); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(firstUser)); + } + + @Test // DATAJPA-218 + public void findAllByExampleWithAssociation() { + + flushTestUsers(); + + firstUser.setManager(secondUser); + thirdUser.setManager(firstUser); + repository.save(Arrays.asList(firstUser, thirdUser)); + + User manager = new User(); + manager.setLastname("Arrasz"); + manager.setAge(secondUser.getAge()); + manager.setCreatedAt(null); + + User prototype = new User(); + prototype.setCreatedAt(null); + prototype.setManager(manager); + + Example example = Example.of(prototype, matching().withIgnorePaths("age")); + List users = repository.findAll(example); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(firstUser)); + } + + @Test // DATAJPA-218 + public void findAllByExampleWithEmbedded() { + + flushTestUsers(); + + firstUser.setAddress(new Address("germany", "dresden", "", "")); + repository.save(firstUser); + + User prototype = new User(); + prototype.setCreatedAt(null); + prototype.setAddress(new Address("germany", null, null, null)); + + Example example = Example.of(prototype, matching().withIgnorePaths("age")); + List users = repository.findAll(example); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(firstUser)); + } + + @Test // DATAJPA-218 + public void findAllByExampleWithStartingStringMatcher() { + + flushTestUsers(); + + User prototype = new User(); + prototype.setFirstname("Ol"); + + Example example = Example.of(prototype, + matching().withStringMatcher(StringMatcher.STARTING).withIgnorePaths("age", "createdAt")); + List users = repository.findAll(example); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(firstUser)); + } + + @Test // DATAJPA-218 + public void findAllByExampleWithEndingStringMatcher() { + + flushTestUsers(); + + User prototype = new User(); + prototype.setFirstname("ver"); + + Example example = Example.of(prototype, + matching().withStringMatcher(StringMatcher.ENDING).withIgnorePaths("age", "createdAt")); + List users = repository.findAll(example); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(firstUser)); + } + + @Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218 + public void findAllByExampleWithRegexStringMatcher() { + + flushTestUsers(); + + User prototype = new User(); + prototype.setFirstname("^Oliver$"); + + Example example = Example.of(prototype, matching().withStringMatcher(StringMatcher.REGEX)); + repository.findAll(example); + } + + @Test // DATAJPA-218 + public void findAllByExampleWithIgnoreCase() { + + flushTestUsers(); + + User prototype = new User(); + prototype.setFirstname("oLiVer"); + + Example example = Example.of(prototype, matching().withIgnoreCase().withIgnorePaths("age", "createdAt")); + + List users = repository.findAll(example); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(firstUser)); + } + + @Test // DATAJPA-218 + public void findAllByExampleWithStringMatcherAndIgnoreCase() { + + flushTestUsers(); + + User prototype = new User(); + prototype.setFirstname("oLiV"); + + Example example = Example.of(prototype, + matching().withStringMatcher(StringMatcher.STARTING).withIgnoreCase().withIgnorePaths("age", "createdAt")); + + List users = repository.findAll(example); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(firstUser)); + } + + @Test // DATAJPA-218 + public void findAllByExampleWithIncludeNull() { + + // something is wrong with OpenJPA - I do not know what + Assume.assumeThat(PersistenceProvider.fromEntityManager(em), not(equalTo(PersistenceProvider.OPEN_JPA))); + + flushTestUsers(); + + firstUser.setAddress(new Address("andor", "caemlyn", "", "")); + + User fifthUser = new User(); + fifthUser.setEmailAddress("foo@bar.com"); + fifthUser.setActive(firstUser.isActive()); + fifthUser.setAge(firstUser.getAge()); + fifthUser.setFirstname(firstUser.getFirstname()); + fifthUser.setLastname(firstUser.getLastname()); + + repository.save(Arrays.asList(firstUser, fifthUser)); + + User prototype = new User(); + prototype.setFirstname(firstUser.getFirstname()); + + Example example = Example.of(prototype, matching().withIncludeNullValues().withIgnorePaths("id", "binaryData", + "lastname", "emailAddress", "age", "createdAt")); + + List users = repository.findAll(example); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(fifthUser)); + } + + @Test // DATAJPA-218 + public void findAllByExampleWithPropertySpecifier() { + + flushTestUsers(); + + User prototype = new User(); + prototype.setFirstname("oLi"); + + Example example = Example.of(prototype, matching().withIgnoreCase().withIgnorePaths("age", "createdAt") + .withMatcher("firstname", new GenericPropertyMatcher().startsWith())); + + List users = repository.findAll(example); + + assertThat(users, hasSize(1)); + assertThat(users.get(0), is(firstUser)); + } + + @Test // DATAJPA-218 + public void findAllByExampleWithSort() { + + flushTestUsers(); + + User user1 = new User("Oliver", "Srping", "o@s.de"); + user1.setAge(30); + + repository.save(user1); + + User prototype = new User(); + prototype.setFirstname("oLi"); + + Example example = Example.of(prototype, matching().withIgnoreCase().withIgnorePaths("age", "createdAt") + .withStringMatcher(StringMatcher.STARTING).withIgnoreCase()); + + List users = repository.findAll(example, new Sort(DESC, "age")); + + assertThat(users, hasSize(2)); + assertThat(users.get(0), is(user1)); + assertThat(users.get(1), is(firstUser)); + } + + @Test // DATAJPA-218 + public void findAllByExampleWithPageable() { + + flushTestUsers(); + + for (int i = 0; i < 99; i++) { + User user1 = new User("Oliver-" + i, "Srping", "o" + i + "@s.de"); + user1.setAge(30 + i); + + repository.save(user1); + } + + User prototype = new User(); + prototype.setFirstname("oLi"); + + Example example = Example.of(prototype, matching().withIgnoreCase().withIgnorePaths("age", "createdAt") + .withStringMatcher(StringMatcher.STARTING).withIgnoreCase()); + + Page users = repository.findAll(example, new PageRequest(0, 10, new Sort(DESC, "age"))); + + assertThat(users.getSize(), is(10)); + assertThat(users.hasNext(), is(true)); + assertThat(users.getTotalElements(), is(100L)); + } + + @Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218 + public void findAllByExampleShouldNotAllowCycles() { + + flushTestUsers(); + + User user1 = new User(); + user1.setFirstname("user1"); + + user1.setManager(user1); + + Example example = Example.of(user1, matching().withIgnoreCase().withIgnorePaths("age", "createdAt") + .withStringMatcher(StringMatcher.STARTING).withIgnoreCase()); + + repository.findAll(example, new PageRequest(0, 10, new Sort(DESC, "age"))); + } + + @Test(expected = InvalidDataAccessApiUsageException.class) // DATAJPA-218 + public void findAllByExampleShouldNotAllowCyclesOverSeveralInstances() { + + flushTestUsers(); + + User user1 = new User(); + user1.setFirstname("user1"); + + User user2 = new User(); + user2.setFirstname("user2"); + + user1.setManager(user2); + user2.setManager(user1); + + Example example = Example.of(user1, matching().withIgnoreCase().withIgnorePaths("age", "createdAt") + .withStringMatcher(StringMatcher.STARTING).withIgnoreCase()); + + repository.findAll(example, new PageRequest(0, 10, new Sort(DESC, "age"))); + } + + @Test // DATAJPA-218 + public void findOneByExampleWithExcludedAttributes() { + + flushTestUsers(); + + User prototype = new User(); + prototype.setAge(28); + + Example example = Example.of(prototype, matching().withIgnorePaths("createdAt")); + User users = repository.findOne(example); + + assertThat(users, is(firstUser)); + } + + @Test // DATAJPA-218 + public void countByExampleWithExcludedAttributes() { + + flushTestUsers(); + + User prototype = new User(); + prototype.setAge(28); + + Example example = Example.of(prototype, matching().withIgnorePaths("createdAt")); + long count = repository.count(example); + + assertThat(count, is(1L)); + } + + @Test // DATAJPA-218 + public void existsByExampleWithExcludedAttributes() { + + flushTestUsers(); + + User prototype = new User(); + prototype.setAge(28); + + Example example = Example.of(prototype, matching().withIgnorePaths("createdAt")); + boolean exists = repository.exists(example); + + assertThat(exists, is(true)); + } + + @Test // DATAJPA-905 + public void excutesPagedSpecificationSettingAnOrder() { + + flushTestUsers(); + + Page result = repository.findAll(where(userHasLastnameLikeWithSort("e")), new PageRequest(0, 1)); + + assertThat(result.getTotalElements(), is(2L)); + assertThat(result.getNumberOfElements(), is(1)); + assertThat(result.getContent().get(0), is(thirdUser)); + } + + @Test // DATAJPA-1172 + public void queryProvidesCorrectNumberOfParametersForNativeQuery() { + + Query query = em.createNativeQuery("select 1 from User where firstname=? and lastname=?"); + assertThat(query.getParameters(), hasSize(2)); + } + + @Test // DATAJPA-1185 + public void dynamicProjectionReturningStream() { + + flushTestUsers(); + + Stream users = repository.findAsStreamByFirstnameLike("%O%", User.class); + + assertThat(users.collect(Collectors.toList()), hasSize(1)); + } + + @Test // DATAJPA-1185 + public void dynamicProjectionReturningList() { + + flushTestUsers(); + + List users = repository.findAsListByFirstnameLike("%O%", User.class); + + assertThat(users, hasSize(1)); + } + + @Test // DATAJPA-1179 + public void duplicateSpelsWorkAsIntended() { + + flushTestUsers(); + + List users = repository.findUsersByDuplicateSpel("Oliver"); + + assertThat(users, hasSize(1)); + } + + @Test // DATAJPA-980 + public void supportsProjectionsWithNativeQueries() { + + Assume.assumeTrue(Version.getVersionString().startsWith("5.2")); + + flushTestUsers(); + + User user = repository.findAll().get(0); + + NameOnly result = repository.findByNativeQuery(user.getId()); + + assertThat(result.getFirstname(), is(user.getFirstname())); + assertThat(result.getLastname(), is(user.getLastname())); + } + + private Page executeSpecWithSort(Sort sort) { + + flushTestUsers(); + + Specification spec = where(userHasFirstname("Oliver")).or(userHasLastname("Matthews")); + + Page result = repository.findAll(spec, new PageRequest(0, 1, sort)); + assertThat(result.getTotalElements(), is(2L)); + return result; + } +} diff --git a/src/test/java/org/springframework/data/jpa/repository/sample/UserRepository.java b/src/test/java/org/springframework/data/jpa/repository/sample/UserRepository.java index 7bc732150..7262f929d 100644 --- a/src/test/java/org/springframework/data/jpa/repository/sample/UserRepository.java +++ b/src/test/java/org/springframework/data/jpa/repository/sample/UserRepository.java @@ -475,6 +475,13 @@ public interface UserRepository @Query(value = "SELECT firstname, lastname from SD_User WHERE id = ?1", nativeQuery = true) NameOnly findByNativeQuery(Integer id); + // DATAJPA-1185 + Stream findAsStreamByFirstnameLike(String name, Class projectionType); + + // DATAJPA-1185 + List findAsListByFirstnameLike(String name, Class projectionType); + + interface RolesAndFirstname { String getFirstname();