org.springframework.data.domain.Example Java Examples

The following examples show how to use org.springframework.data.domain.Example. 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 File: ArangoRepositoryTest.java    From spring-data with 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 #2
Source File: ArangoRepositoryTest.java    From spring-data with 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 #3
Source File: UseCase2DTOService.java    From celerio-angular-quickstart with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: PassengerRepositoryIntegrationTest.java    From tutorials with 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 #5
Source File: UseCase1DTOService.java    From celerio-angular-quickstart with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: ScopeServiceTest.java    From heimdall with 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 #7
Source File: ResourceServiceTest.java    From heimdall with 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 #8
Source File: SimpleEbeanRepository.java    From spring-data-ebean with Apache License 2.0 5 votes vote down vote up
@Override
public <S extends T> Page<S> findAll(String fetchPath, Example<S> example, Pageable pageable) {
    PagedList<S> pagedList = queryByExample(fetchPath, example)
            .setMaxRows(pageable.getPageSize())
            .setFirstRow((int) pageable.getOffset())
            .setOrder(Converters.convertToEbeanOrderBy(pageable.getSort()))
            .findPagedList();
    return Converters.convertToSpringDataPage(pagedList, pageable.getSort());
}
 
Example #9
Source File: UserRepository.java    From celerio-angular-quickstart with Apache License 2.0 5 votes vote down vote up
default List<User> complete(String query, int maxResults) {
    User probe = new User();
    probe.setLogin(query);

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

    Page<User> page = findAll(Example.of(probe, matcher), new PageRequest(0, maxResults));
    return page.getContent();
}
 
Example #10
Source File: CommentServiceImpl.java    From Fame with MIT License 5 votes vote down vote up
@Override
@Cacheable(value = COMMENT_CACHE_NAME, key = "'article_comments['+#page+':'+#limit+':'+#articleId+']'")
public Page<Comment> getCommentsByArticleId(Integer page, Integer limit, Integer articleId) {
    Comment record = new Comment();
    record.setArticleId(articleId);
    record.setStatus(CommentStatus.NORMAL);
    Page<Comment> result = commentRepository.findAll(Example.of(record), PageRequest.of(page, limit, FameUtil.sortDescById()));

    result.forEach(comments -> {
        String content = FameUtil.contentTransform(comments.getContent(), false, true, null);
        comments.setContent(content);
    });

    return result;
}
 
Example #11
Source File: JpaEventDao.java    From Spring-Security-Third-Edition with 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 File: SimpleDatastoreRepositoryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void countByExample() {
	Example<Object> example2 = Example.of(new Object());

	doAnswer((invocationOnMock) -> Arrays.asList(1, 2, 3))
			.when(this.datastoreTemplate).keyQueryByExample(same(example2), isNull());

	assertThat(this.simpleDatastoreRepository.count(example2)).isEqualTo(3);

	verify(this.datastoreTemplate, times(1)).keyQueryByExample(same(example2), isNull());
}
 
Example #13
Source File: LinkServiceImpl.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean existByName(String name) {
    Assert.hasText(name, "Link name must not be blank");
    Link link = new Link();
    link.setName(name);

    return linkRepository.exists(Example.of(link));
}
 
Example #14
Source File: JpaEventDao.java    From Spring-Security-Third-Edition with 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 File: JpaEventDao.java    From Spring-Security-Third-Edition with 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 File: JpaEventDao.java    From Spring-Security-Third-Edition with 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 #17
Source File: JpaEventDao.java    From Spring-Security-Third-Edition with 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 #18
Source File: JpaEventDao.java    From Spring-Security-Third-Edition with 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 #19
Source File: ProviderService.java    From heimdall with 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 #20
Source File: SimpleDatastoreRepositoryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void existsByExampleTrue() {
	Example<Object> example2 = Example.of(new Object());

	doAnswer((invocationOnMock) -> Arrays.asList(1))
			.when(this.datastoreTemplate).keyQueryByExample(same(example2),
					eq(new DatastoreQueryOptions.Builder().setLimit(1).build()));

	assertThat(this.simpleDatastoreRepository.exists(example2)).isEqualTo(true);

	verify(this.datastoreTemplate, times(1)).keyQueryByExample(same(example2),
			eq(new DatastoreQueryOptions.Builder().setLimit(1).build()));
}
 
Example #21
Source File: DatastoreTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void queryByExampleDeepPathTest() {
	this.expectedEx.expect(DatastoreDataException.class);
	this.expectedEx.expectMessage("Ignored paths deeper than 1 are not supported");

	this.datastoreTemplate.queryByExample(
			Example.of(new SimpleTestEntity(), ExampleMatcher.matching().withIgnorePaths("intField.a")), null);
}
 
Example #22
Source File: DatastoreTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void queryByExampleOptions() {
	EntityQuery.Builder builder = Query.newEntityQueryBuilder().setKind("test_kind");
	this.datastoreTemplate.queryByExample(
			Example.of(this.simpleTestEntity, ExampleMatcher.matching().withIgnorePaths("id")),
			new DatastoreQueryOptions.Builder().setLimit(10).setOffset(1).setSort(Sort.by("intField"))
					.build());

	StructuredQuery.CompositeFilter filter = StructuredQuery.CompositeFilter
			.and(PropertyFilter.eq("color", "simple_test_color"),
					PropertyFilter.eq("int_field", 1));
	verify(this.datastore, times(1)).run(builder.setFilter(filter)
			.addOrderBy(StructuredQuery.OrderBy.asc("int_field")).setLimit(10).setOffset(1).build());
}
 
Example #23
Source File: UserRepositoryIntegrationTests.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
/**
 * @see #153
 */
@Test
public void substringMatching() {

	Example<Person> example = Example.of(new Person("er", null, null), matching(). //
			withStringMatcher(StringMatcher.ENDING));

	assertThat(repository.findAll(example)).containsExactlyInAnyOrder(skyler, walter);
}
 
Example #24
Source File: JpaEventDao.java    From Spring-Security-Third-Edition with 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 #25
Source File: JpaEventDao.java    From Spring-Security-Third-Edition with 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 #26
Source File: JpaEventDao.java    From Spring-Security-Third-Edition with 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 #27
Source File: UserRepositoryIntegrationTests.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
/**
 * @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);
}
 
Example #28
Source File: JpaEventDao.java    From Spring-Security-Third-Edition with 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 #29
Source File: ConferenceServiceImpl.java    From graphql-java-demo with 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 #30
Source File: SimpleReactiveQueryByExampleExecutor.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@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());
}