Java Code Examples for org.springframework.data.domain.Example

The following examples show how to use org.springframework.data.domain.Example. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: heimdall   Source File: ResourceServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void listResourcesWithPageable() {

     PageableDTO pageableDTO = new PageableDTO();
     pageableDTO.setLimit(10);
     pageableDTO.setOffset(0);

     ArrayList<Resource> listResources = new ArrayList<>();

     this.resource.setName("Resource Name");

     listResources.add(resource);

     Page<Resource> page = new PageImpl<>(listResources);

     Mockito.when(apiRepository.findOne(Mockito.anyLong())).thenReturn(api);
     Mockito.when(this.resourceRepository
                            .findAll(Mockito.any(Example.class), Mockito.any(Pageable.class)))
            .thenReturn(page);

     ResourcePage resourcePageResp = this.resourceService.list(1L, this.resourceDTO, pageableDTO);

     assertEquals(1L, resourcePageResp.getTotalElements());
     Mockito.verify(this.resourceRepository, Mockito.times(1))
            .findAll(Mockito.any(Example.class), Mockito.any(Pageable.class));
}
 
Example 2
Source Project: tutorials   Source File: PassengerRepositoryIntegrationTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenPassengers_whenFindByIgnoringMatcher_thenExpectedReturned() {
    Passenger jill = Passenger.from("Jill", "Smith", 50);
    Passenger eve = Passenger.from("Eve", "Jackson", 95);
    Passenger fred = Passenger.from("Fred", "Bloggs", 22);
    Passenger siya = Passenger.from("Siya", "Kolisi", 85);
    Passenger ricki = Passenger.from("Ricki", "Bobbie", 36);

    ExampleMatcher ignoringExampleMatcher = ExampleMatcher.matchingAny().withMatcher("lastName",
        ExampleMatcher.GenericPropertyMatchers.startsWith().ignoreCase()).withIgnorePaths("firstName", "seatNumber");

    Example<Passenger> example = Example.of(Passenger.from(null, "b", null),
        ignoringExampleMatcher);

    List<Passenger> passengers = repository.findAll(example);

    assertThat(passengers, contains(fred, ricki));
    assertThat(passengers, not(contains(jill)));
    assertThat(passengers, not(contains(eve)));
    assertThat(passengers, not(contains(siya)));
}
 
Example 3
Source Project: spring-data   Source File: ArangoRepositoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void endingWithByExampleNestedIncludeNullTest() {
	final List<Customer> toBeRetrieved = new LinkedList<>();
	final Customer check = new Customer("Abba", "Bbaaaa", 100);
	final Customer nested = new Customer("$B*\\wa?[a.b]baaa", "", 67);
	final Customer nested2 = new Customer("qwerty", "", 10);
	nested2.setAddress(new Address("123456"));
	nested.setNestedCustomer(nested2);
	check.setNestedCustomer(nested);
	toBeRetrieved.add(check);
	toBeRetrieved.add(new Customer("B", "", 43));
	toBeRetrieved.add(new Customer("C", "", 76));
	repository.saveAll(toBeRetrieved);
	final Customer exampleCustomer = new Customer("Abba", "Bbaaaa", 100);
	final Customer nested3 = new Customer("B*\\wa?[a.b]baAa", "", 66);
	nested3.setNestedCustomer(nested2);
	exampleCustomer.setNestedCustomer(nested3);
	final Example<Customer> example = Example.of(exampleCustomer,
		ExampleMatcher.matching().withMatcher("nestedCustomer.name", match -> match.endsWith())
				.withIgnorePaths(new String[] { "arangoId", "id", "key", "rev" })
				.withIgnoreCase("nestedCustomer.name").withIncludeNullValues()
				.withTransformer("nestedCustomer.age", o -> Optional.of(Integer.valueOf(o.get().toString()) + 1)));
	final Customer retrieved = repository.findOne(example).get();
	assertEquals(check, retrieved);
}
 
Example 4
@Transactional(readOnly = true)
public PageResponse<UseCase1DTO> findAll(PageRequestByExample<UseCase1DTO> req) {
    Example<UseCase1> example = null;
    UseCase1 useCase1 = toEntity(req.example);

    if (useCase1 != null) {
        ExampleMatcher matcher = ExampleMatcher.matching() //
                .withMatcher(UseCase1_.dummy.getName(), match -> match.ignoreCase().startsWith());

        example = Example.of(useCase1, matcher);
    }

    Page<UseCase1> page;
    if (example != null) {
        page = useCase1Repository.findAll(example, req.toPageable());
    } else {
        page = useCase1Repository.findAll(req.toPageable());
    }

    List<UseCase1DTO> content = page.getContent().stream().map(this::toDTO).collect(Collectors.toList());
    return new PageResponse<>(page.getTotalPages(), page.getTotalElements(), content);
}
 
Example 5
Source Project: heimdall   Source File: ScopeServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void listPageTest() {
    ScopeDTO scopeDTO = new ScopeDTO();
    scopeDTO.setName("Scope");
    scopeDTO.setDescription("Scope description");
    List<Scope> scopesExpected = new ArrayList<>();
    scopesExpected.add(scope);

    Page<Scope> scopes = createPageScope(scopesExpected);

    PageableDTO pageableDTO = new PageableDTO();
    pageableDTO.setLimit(10);
    pageableDTO.setOffset(0);

    Mockito.when(apiService.find(Mockito.anyLong())).thenReturn(scope.getApi());
    Mockito.when(scopeRepository.findAll(Mockito.any(Example.class), Mockito.any(Pageable.class))).thenReturn(scopes);

    ScopePage scopePage = scopeService.list(scope.getApi().getId(), scopeDTO, pageableDTO);

    assertEquals(scopes.getContent(), scopePage.getContent());
}
 
Example 6
Source Project: spring-data   Source File: ArangoRepositoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void countByExampleTest() {
	final List<Customer> toBeRetrieved = new LinkedList<>();
	toBeRetrieved.add(new Customer("A", "Z", 0));
	toBeRetrieved.add(new Customer("B", "X", 0));
	toBeRetrieved.add(new Customer("B", "Y", 0));
	toBeRetrieved.add(new Customer("C", "V", 0));
	toBeRetrieved.add(new Customer("D", "T", 0));
	toBeRetrieved.add(new Customer("D", "U", 0));
	toBeRetrieved.add(new Customer("E", "S", 0));
	toBeRetrieved.add(new Customer("F", "P", 0));
	toBeRetrieved.add(new Customer("F", "Q", 0));
	toBeRetrieved.add(new Customer("F", "R", 0));
	repository.saveAll(toBeRetrieved);
	final Example<Customer> example = Example.of(new Customer("", "", 0),
		ExampleMatcher.matchingAny().withIgnoreNullValues().withIgnorePaths(new String[] { "location", "alive" }));
	final long size = repository.count(example);
	assertTrue(size == toBeRetrieved.size());
}
 
Example 7
@Transactional(readOnly = true)
public PageResponse<UseCase2DTO> findAll(PageRequestByExample<UseCase2DTO> req) {
    Example<UseCase2> example = null;
    UseCase2 useCase2 = toEntity(req.example);

    if (useCase2 != null) {
        ExampleMatcher matcher = ExampleMatcher.matching() //
                .withMatcher(UseCase2_.dummy.getName(), match -> match.ignoreCase().startsWith());

        example = Example.of(useCase2, matcher);
    }

    Page<UseCase2> page;
    if (example != null) {
        page = useCase2Repository.findAll(example, req.toPageable());
    } else {
        page = useCase2Repository.findAll(req.toPageable());
    }

    List<UseCase2DTO> content = page.getContent().stream().map(this::toDTO).collect(Collectors.toList());
    return new PageResponse<>(page.getTotalPages(), page.getTotalElements(), content);
}
 
Example 8
Source Project: celerio-angular-quickstart   Source File: RoleRepository.java    License: Apache License 2.0 5 votes vote down vote up
default List<Role> complete(String query, int maxResults) {
    Role probe = new Role();
    probe.setRoleName(query);

    ExampleMatcher matcher = ExampleMatcher.matching() //
            .withMatcher(Role_.roleName.getName(), match -> match.ignoreCase().startsWith());

    Page<Role> page = findAll(Example.of(probe, matcher), new PageRequest(0, maxResults));
    return page.getContent();
}
 
Example 9
@Override
public <S extends T> Flux<S> findAll(Example<S> example) {

	Predicate predicate = Predicate.create(mappingContext, example);
	Statement statement = predicate.useWithReadingFragment(cypherGenerator::prepareMatchOf)
		.returning(asterisk())
		.build();

	return this.neo4jOperations.findAll(statement, predicate.getParameters(), example.getProbeType());
}
 
Example 10
Source Project: heimdall   Source File: DeveloperServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void listArray() {
    PageableDTO pageableDTO = new PageableDTO();
    pageableDTO.setLimit(10);
    pageableDTO.setOffset(0);
    List<Developer> developers = new ArrayList<>();
    developers.add(developer);

    Mockito.when(developerRepository.findAll(Mockito.any(Example.class))).thenReturn(developers);
    List<Developer> developersResult = developerService.list(developerDTO);

    assertEquals(developers, developersResult);
}
 
Example 11
Source Project: Spring-Security-Third-Edition   Source File: JpaEventDao.java    License: MIT License 5 votes vote down vote up
@Override
@Transactional(readOnly = true)
public List<Event> findForUser(final int userId) {
    Event example = new Event();
    CalendarUser cu = new CalendarUser();
    cu.setId(userId);
    example.setOwner(cu);

    return repository.findAll(Example.of(example));
}
 
Example 12
Source Project: Spring-Security-Third-Edition   Source File: JpaEventDao.java    License: MIT License 5 votes vote down vote up
@Override
@Transactional(readOnly = true)
public List<Event> findForUser(final int userId) {
    Event example = new Event();
    CalendarUser cu = new CalendarUser();
    cu.setId(userId);
    example.setOwner(cu);

    return repository.findAll(Example.of(example));
}
 
Example 13
Source Project: sdn-rx   Source File: SimpleQueryByExampleExecutor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <S extends T> List<S> findAll(Example<S> example) {

	Predicate predicate = Predicate.create(mappingContext, example);
	Statement statement = predicate.useWithReadingFragment(cypherGenerator::prepareMatchOf)
		.returning(asterisk())
		.build();

	return this.neo4jOperations.findAll(statement, predicate.getParameters(), example.getProbeType());
}
 
Example 14
Source Project: Spring-Security-Third-Edition   Source File: JpaEventDao.java    License: MIT License 5 votes vote down vote up
@Override
@Transactional(readOnly = true)
public List<Event> findForUser(final int userId) {
    Event example = new Event();
    CalendarUser cu = new CalendarUser();
    cu.setId(userId);
    example.setOwner(cu);

    return repository.findAll(Example.of(example));
}
 
Example 15
Source Project: Spring-Security-Third-Edition   Source File: JpaEventDao.java    License: MIT License 5 votes vote down vote up
@Override
@Transactional(readOnly = true)
public List<Event> findForUser(final int userId) {
    Event example = new Event();
    CalendarUser cu = new CalendarUser();
    cu.setId(userId);
    example.setOwner(cu);

    return repository.findAll(Example.of(example));
}
 
Example 16
Source Project: danyuan-application   Source File: SysRuleInfoService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws IOException
 * @throws ParseException
 * @param i
 * @方法名 startTask
 * @功能 TODO(这里用一句话描述这个方法的作用)
 * @参数 @param list
 * @参数 @return
 * @返回 String
 * @author Administrator
 * @throws
 */
public String startTask(List<SysCrawlerTaskInfo> list, int i) throws ParseException, IOException {
	for (SysCrawlerTaskInfo sysCrawlerTaskInfo : list) {
		SysCrawlerRulerInfo sysCrawlerRulerInfo = new SysCrawlerRulerInfo();
		sysCrawlerRulerInfo.setTaskUuid(sysCrawlerTaskInfo.getUuid());
		Example<SysCrawlerRulerInfo> example = Example.of(sysCrawlerRulerInfo);
		List<SysCrawlerRulerInfo> ruleList = sysCrawlerRulerInfoDao.findAll(example);
		for (SysCrawlerRulerInfo sysCrawlerRulerInfo2 : ruleList) {
			// 去重
			if (!sysCrawlerRulerInfo2.getStatue().equals(i + "")) {
				sysCrawlerRulerInfo2.setStatue(i + "");
				// 修改状态
				sysCrawlerRulerInfoDao.save(sysCrawlerRulerInfo2);
				if (i == 1) {
					// 启动任务
					Map<String, String> map = new HashMap<>();
					map.put("uuid", sysCrawlerRulerInfo2.getUuid());
					map.put("taskUuid", sysCrawlerRulerInfo2.getUuid());
					map.put("contentInfo", sysCrawlerRulerInfo2.getContentJsonInfo());
					map.put("delete", sysCrawlerRulerInfo2.getDeleteFlag() + "");
					map.put("statue", sysCrawlerRulerInfo2.getStatue());
					HttpUtil.postJson("http://127.0.0.1:3000/crawler", map, "UTF-8");
				}
			}
		}
	}
	return "1";
}
 
Example 17
Source Project: spring-data   Source File: ArangoRepositoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void findAllPageableByExampleTest() {
	final List<Customer> toBeRetrieved = new LinkedList<>();
	toBeRetrieved.add(new Customer("A", "Z", 0));
	toBeRetrieved.add(new Customer("B", "X", 0));
	toBeRetrieved.add(new Customer("B", "Y", 0));
	toBeRetrieved.add(new Customer("C", "V", 0));
	toBeRetrieved.add(new Customer("D", "T", 0));
	toBeRetrieved.add(new Customer("D", "U", 0));
	toBeRetrieved.add(new Customer("E", "S", 0));
	toBeRetrieved.add(new Customer("F", "P", 0));
	toBeRetrieved.add(new Customer("F", "Q", 0));
	toBeRetrieved.add(new Customer("F", "R", 0));
	repository.saveAll(toBeRetrieved);
	repository.save(new Customer("A", "A", 1));
	final Example<Customer> example = Example.of(new Customer("", "", 0),
		ExampleMatcher.matchingAny().withIgnoreNullValues().withIgnorePaths(new String[] { "location", "alive" }));
	final List<Sort.Order> orders = new LinkedList<>();
	orders.add(new Sort.Order(Sort.Direction.ASC, "name"));
	orders.add(new Sort.Order(Sort.Direction.ASC, "surname"));
	final Sort sort = Sort.by(orders);
	final int pageNumber = 1;
	final int pageSize = 3;
	final Page<Customer> retrievedPage = repository.findAll(example, PageRequest.of(pageNumber, pageSize, sort));
	assertEquals(toBeRetrieved.size(), retrievedPage.getTotalElements());
	assertEquals(pageNumber, retrievedPage.getNumber());
	assertEquals(pageSize, retrievedPage.getSize());
	assertEquals((toBeRetrieved.size() + pageSize - 1) / pageSize, retrievedPage.getTotalPages());
	final List<Customer> expected = toBeRetrieved.subList(pageNumber * pageSize, (pageNumber + 1) * pageSize);
	assertTrue(equals(expected, retrievedPage, cmp, eq, true));
}
 
Example 18
Source Project: sdn-rx   Source File: RepositoryIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void findAllByExampleWithSort(@Autowired PersonRepository repository) {

	Example<PersonWithAllConstructor> example = Example.of(personExample(TEST_PERSON_SAMEVALUE));
	List<PersonWithAllConstructor> persons = repository.findAll(example, Sort.by(Sort.Direction.DESC, "name"));

	assertThat(persons).containsExactly(person2, person1);
}
 
Example 19
Source Project: sdn-rx   Source File: RepositoryIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void findAllByExampleWithPagination(@Autowired PersonRepository repository) {

	Example<PersonWithAllConstructor> example = Example.of(personExample(TEST_PERSON_SAMEVALUE));
	Iterable<PersonWithAllConstructor> persons = repository
		.findAll(example, PageRequest.of(1, 1, Sort.by("name")));

	assertThat(persons).containsExactly(person2);
}
 
Example 20
/**
 * @see #153
 */
@Test
public void findAllRelativesBySimpleExample() {

	Example<Relative> example = Example.of(new Relative(".*", null, null), //
			matching().withStringMatcher(StringMatcher.REGEX));

	assertThat(contactRepository.findAll(example), containsInAnyOrder(hank, marie));
	assertThat(contactRepository.findAll(example), not(containsInAnyOrder(skyler, walter, flynn)));
}
 
Example 21
default List<UseCase1> complete(String query, int maxResults) {
    UseCase1 probe = new UseCase1();
    probe.setDummy(query);

    ExampleMatcher matcher = ExampleMatcher.matching() //
            .withMatcher(UseCase1_.dummy.getName(), match -> match.ignoreCase().startsWith());

    Page<UseCase1> page = findAll(Example.of(probe, matcher), new PageRequest(0, maxResults));
    return page.getContent();
}
 
Example 22
Source Project: Spring-Security-Third-Edition   Source File: JpaEventDao.java    License: MIT License 5 votes vote down vote up
@Override
@Transactional(readOnly = true)
public List<Event> findForUser(final int userId) {
    Event example = new Event();
    CalendarUser cu = new CalendarUser();
    cu.setId(userId);
    example.setOwner(cu);

    return repository.findAll(Example.of(example));
}
 
Example 23
Source Project: sdn-rx   Source File: ReactiveRepositoryIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void findAllByExampleWithSort(@Autowired ReactivePersonRepository repository) {
	Example<PersonWithAllConstructor> example = Example.of(personExample(TEST_PERSON_SAMEVALUE));

	StepVerifier.create(repository.findAll(example, Sort.by(Sort.Direction.DESC, "name"))).expectNext(person2, person1)
		.verifyComplete();
}
 
Example 24
Source Project: Spring-Security-Third-Edition   Source File: JpaEventDao.java    License: MIT License 5 votes vote down vote up
@Override
@Transactional(readOnly = true)
public List<Event> findForUser(final String email) {
    Event example = new Event();
    CalendarUser cu = new CalendarUser();
    cu.setEmail(email);
    example.setOwner(cu);

    return repository.findAll(Example.of(example));
}
 
Example 25
Source Project: spring-data   Source File: SimpleArangoRepository.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Counts the number of documents in the collection which match with the given example
 *
 * @param example
 *            example object to construct query with
 * @param <S>
 * @return number of matching documents found
 */
@Override
public <S extends T> long count(final Example<S> example) {
	final Map<String, Object> bindVars = new HashMap<>();
	final String predicate = exampleConverter.convertExampleToPredicate(example, bindVars);
	final String filter = predicate.length() == 0 ? "" : " FILTER " + predicate;
	final String query = String.format("FOR e IN %s%s COLLECT WITH COUNT INTO length RETURN length",
		getCollectionName(), filter);
	final ArangoCursor<Long> cursor = arangoOperations.query(query, bindVars, null, Long.class);
	return cursor.next();
}
 
Example 26
default List<Passport> complete(String query, int maxResults) {
    Passport probe = new Passport();
    probe.setPassportNumber(query);

    ExampleMatcher matcher = ExampleMatcher.matching() //
            .withMatcher(Passport_.passportNumber.getName(), match -> match.ignoreCase().startsWith());

    Page<Passport> page = findAll(Example.of(probe, matcher), new PageRequest(0, maxResults));
    return page.getContent();
}
 
Example 27
Source Project: heimdall   Source File: ProviderService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates a list of {@link Provider} from a request
 *
 * @param providerDTO The {@link ProviderDTO}
 * @return The list of {@link Provider}
 */
public List<Provider> listWithFilter(ProviderDTO providerDTO) {

    Provider provider = GenericConverter.mapper(providerDTO, Provider.class);
    Example<Provider> example = Example.of(provider,
            ExampleMatcher.matching().withIgnorePaths("providerDefault").withIgnoreCase().withStringMatcher(StringMatcher.CONTAINING));

    return this.providerRepository.findAll(example);
}
 
Example 28
Source Project: graphql-java-demo   Source File: ConferenceServiceImpl.java    License: MIT License 5 votes vote down vote up
public List<Conference> find(final Conference filter) {
    if (filter == null) {
        return conferenceRepository.findAll();
    }

    ExampleMatcher matcher = ExampleMatcher.matching()
            .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
            .withIgnoreCase();

    return StreamSupport.stream(conferenceRepository.findAll(Example.of(filter, matcher)).spliterator(), false)
            .collect(Collectors.toList());
}
 
Example 29
Source Project: Spring-Security-Third-Edition   Source File: JpaEventDao.java    License: MIT License 5 votes vote down vote up
@Override
@Transactional(readOnly = true)
public List<Event> findForUser(final int userId) {
    Event example = new Event();
    CalendarUser cu = new CalendarUser();
    cu.setId(userId);
    example.setOwner(cu);

    return repository.findAll(Example.of(example));
}
 
Example 30
/**
 * @see #153
 */
@Test
public void regexMatching() {

	Example<Person> example = Example.of(new Person("(Skyl|Walt)er", null, null), matching(). //
			withMatcher("firstname", matcher -> matcher.regex()));

	assertThat(repository.findAll(example)).contains(skyler, walter);
}