Java Code Examples for org.springframework.data.domain.Example#of()

The following examples show how to use org.springframework.data.domain.Example#of() . 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 7 votes vote down vote up
@Test
public void findAllSortByExampleTest() {
	final List<Customer> toBeRetrieved = new LinkedList<>();
	toBeRetrieved.add(new Customer("A", "Z", 0));
	toBeRetrieved.add(new Customer("B", "C", 0));
	toBeRetrieved.add(new Customer("B", "D", 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 Iterable<Customer> retrieved = repository.findAll(example, sort);
	assertTrue(equals(toBeRetrieved, retrieved, cmp, eq, true));
}
 
Example 2
Source File: QueryTests.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Test
public void testSingle() {
	// tag::example-mono[]
	Employee e = new Employee();
	e.setFirstName("Bilbo");
	Example<Employee> example = Example.of(e);
	// end::example-mono[]

	// tag::query-mono[]
	Mono<Employee> singleEmployee = repository.findOne(example);
	// end::query-mono[]

	StepVerifier.create(singleEmployee)
		.expectNextMatches(employee -> {
			assertThat(employee).hasNoNullFieldsOrProperties();
			assertThat(employee.getFirstName()).isEqualTo("Bilbo");
			assertThat(employee.getLastName()).isEqualTo("Baggins");
			assertThat(employee.getRole()).isEqualTo("burglar");
			return true;
		})
		.expectComplete()
		.verify();
}
 
Example 3
Source File: PermissionService.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public List<PermissionEntity> permissionList(AccountEntity accountEntity) {
    PermissionEntity permissionEntity = new PermissionEntity();
    permissionEntity.setBrokerId(accountEntity.getBrokerId());
    // execute select
    Example<PermissionEntity> entityExample = Example.of(permissionEntity);
    return permissionRepository.findAll(entityExample);
}
 
Example 4
Source File: BaseServiceImpl.java    From danyuan-application with Apache License 2.0 5 votes vote down vote up
/**
 * 方法名 : findOne
 * 功 能 : 安条件查询一条
 * 参 数 : @param entity
 * 参 数 : @return
 * 参 考 : @see org.danyuan.application.common.base.BaseService#findOne(java.lang.Object)
 * 作 者 : wang
 */

@Override
public T findOne(T entity) {
	if (entity == null) {
		return null;
	}
	Example<T> example = Example.of(entity);
	Optional<T> optional = baseDao.findOne(example);
	if (optional.isPresent()) {
		return optional.get();
	}
	return null;
}
 
Example 5
Source File: UserRepositoryIntegrationTests.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
/**
 * @see #153
 */
@Test
public void ignorePropertiesAndMatchByAge() {

	Example<User> example = Example.of(flynn, matching(). //
			withIgnorePaths("firstname", "lastname"));

	assertThat(repository.findOne(example)).contains(flynn);
}
 
Example 6
Source File: CarRepositoryIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenExample_whenExists_thenIsTrue() {
    ExampleMatcher modelMatcher = ExampleMatcher.matching()
            .withIgnorePaths("id") // must explicitly ignore -> PK
            .withMatcher("model", ignoreCase());
    Car probe = new Car();
    probe.setModel("bmw");

    Example<Car> example = Example.of(probe, modelMatcher);

    assertThat(repository.exists(example)).isTrue();
}
 
Example 7
Source File: UserRepositoryIntegrationTests.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
/**
 * @see #153
 */
@Test
public void configuringMatchersUsingLambdas() {

	Example<Person> example = Example.of(new Person("Walter", "WHITE", null), matching(). //
			withIgnorePaths("age"). //
			withMatcher("firstname", matcher -> matcher.startsWith()). //
			withMatcher("lastname", matcher -> matcher.ignoreCase()));

	assertThat(repository.findAll(example)).containsExactlyInAnyOrder(flynn, walter);
}
 
Example 8
Source File: MongoOperationsIntegrationTests.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(operations.find(query(byExample(example)), Person.class), hasItems(skyler, walter));
}
 
Example 9
Source File: QueryTests.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Test
public void testMultipleWithTemplate() {
	// tag::flux-template[]
	Employee e = new Employee();
	e.setLastName("baggins"); // Lowercase lastName

	ExampleMatcher matcher = ExampleMatcher.matching()
		.withIgnoreCase()
		.withMatcher("lastName", startsWith())
		.withIncludeNullValues();

	Example<Employee> example = Example.of(e, matcher);

	Flux<Employee> multipleEmployees = operations.find(
		new Query(byExample(example)), Employee.class);
	// end::flux-template[]

	StepVerifier.create(multipleEmployees.collectList())
		.expectNextMatches(employees -> {
			assertThat(employees).hasSize(2);
			assertThat(employees).extracting("firstName")
				.contains("Frodo", "Bilbo");
			return true;
		})
		.expectComplete()
		.verify();
}
 
Example 10
Source File: ModelServiceImpl.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
/**
 * Generic handling of model relations: deleting/adding where needed.
 */
protected void handleModelRelations(AbstractModel bpmnProcessModel, Set<String> idsReferencedInJson, String relationshipType) {

  // Find existing persisted relations
  List<ModelRelation> persistedModelRelations = modelRelationRepository.findByParentModelIdAndType(bpmnProcessModel.getId(), relationshipType);
  
  // if no ids referenced now, just delete them all
  if (idsReferencedInJson == null || idsReferencedInJson.size() == 0) {
    modelRelationRepository.deleteAll(persistedModelRelations);
    return;
  }

  Set<String> alreadyPersistedModelIds = new HashSet<String>(persistedModelRelations.size());
  for (ModelRelation persistedModelRelation : persistedModelRelations) {
    if (!idsReferencedInJson.contains(persistedModelRelation.getModelId())) {
      // model used to be referenced, but not anymore. Delete it.
      modelRelationRepository.delete((ModelRelation) persistedModelRelation);
    } else {
      alreadyPersistedModelIds.add(persistedModelRelation.getModelId());
    }
  }

  // Loop over all referenced ids and see which one are new
  for (String idReferencedInJson : idsReferencedInJson) {
    
    // if model is referenced, but it is not yet persisted = create it
    if (!alreadyPersistedModelIds.contains(idReferencedInJson)) {

      // Check if model actually still exists. Don't create the relationship if it doesn't exist. The client UI will have cope with this too.
      Model md = new Model();
      md.setId(idReferencedInJson);
      Example<Model> example = Example.of(md);
      if (modelRepository.exists(example)) {
        modelRelationRepository.save(new ModelRelation(bpmnProcessModel.getId(), idReferencedInJson, relationshipType));
      }
    }
  }
}
 
Example 11
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 12
Source File: UserRepositoryIntegrationTests.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
/**
 * @see #153
 */
@Test
public void ignorePropertiesAndMatchByAge() {

	Example<Person> example = Example.of(flynn, matching(). //
			withIgnorePaths("firstname", "lastname"));

	assertThat(repository.findOne(example)).contains(flynn);
}
 
Example 13
Source File: ArangoRepositoryTest.java    From spring-data with Apache License 2.0 5 votes vote down vote up
@Test
public void containingExampleTest() {
	final Customer entity = new Customer("name", "surname", 10);
	repository.save(entity);

	final Customer probe = new Customer();
	probe.setName("am");
	final Example<Customer> example = Example.of(probe,
		ExampleMatcher.matching().withStringMatcher(StringMatcher.CONTAINING).withIgnorePaths("arangoId", "id",
			"key", "rev", "surname", "age"));
	final Optional<Customer> retrieved = repository.findOne(example);
	assertThat(retrieved.isPresent(), is(true));
	assertThat(retrieved.get().getName(), is("name"));
}
 
Example 14
Source File: UserRepositoryIntegrationTests.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
/**
 * @see #153
 */
@Test
public void countBySimpleExample() {

	Example<User> example = Example.of(new User(null, "White", null));

	assertThat(repository.count(example)).isEqualTo(3L);
}
 
Example 15
Source File: ArangoRepositoryTest.java    From spring-data with Apache License 2.0 5 votes vote down vote up
@Test
public void startingWithByExampleTest() {
	final List<Customer> toBeRetrieved = new LinkedList<>();
	final Customer check = new Customer("Abba", "Bbaaaa", 100);
	toBeRetrieved.add(check);
	toBeRetrieved.add(new Customer("Baabba", "", 67));
	toBeRetrieved.add(new Customer("B", "", 43));
	toBeRetrieved.add(new Customer("C", "", 76));
	repository.saveAll(toBeRetrieved);
	final Example<Customer> example = Example.of(new Customer(null, "bb", 100), ExampleMatcher.matching()
			.withMatcher("surname", match -> match.startsWith()).withIgnoreCase("surname").withIgnoreNullValues());
	final Customer retrieved = repository.findOne(example).get();
	assertEquals(check, retrieved);
}
 
Example 16
Source File: ScopeService.java    From heimdall with Apache License 2.0 4 votes vote down vote up
/**
 * Generates a paged list of {@link Scope} from a request.
 *
 * @param apiId       The {@link Api} Id
 * @param scopeDTO    The {@link ScopeDTO}
 * @param pageableDTO The {@link PageableDTO}
 * @return The paged {@link Scope} list as a {@link ScopePage} object
 */
@Transactional(readOnly = true)
public ScopePage list(final Long apiId, final ScopeDTO scopeDTO, final PageableDTO pageableDTO) {

    Api api = apiService.find(apiId);

    Scope scope = GenericConverter.mapper(scopeDTO, Scope.class);
    scope.setApi(api);

    Example<Scope> example = Example.of(scope, ExampleMatcher.matching().withIgnorePaths("api.creationDate").withIgnoreCase().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING));

    Pageable pageable = Pageable.setPageable(pageableDTO.getOffset(), pageableDTO.getLimit(), new Sort(Sort.Direction.ASC, "id"));
    Page<Scope> page = scopeRepository.findAll(example, pageable);

    return new ScopePage(PageDTO.build(page));
}
 
Example 17
Source File: BaseServiceImpl.java    From SpringBoot2.0 with Apache License 2.0 4 votes vote down vote up
@Override
public T findUniqueOne(T eg) {
    Example<T> example = Example.of(eg);
    Optional<T> one = dao.findOne(example);
    return one.orElse(null);
}
 
Example 18
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Test
void findAllByExampleWithDifferentMatchers(@Autowired PersonRepository repository) {

	PersonWithAllConstructor person;
	Example<PersonWithAllConstructor> example;
	List<PersonWithAllConstructor> persons;

	person = new PersonWithAllConstructor(null, TEST_PERSON1_NAME, TEST_PERSON2_FIRST_NAME, null, null, null,
		null,
		null, null, null, null);
	example = Example.of(person, ExampleMatcher.matchingAny());

	persons = repository.findAll(example);
	assertThat(persons).containsExactlyInAnyOrder(person1, person2);

	person = new PersonWithAllConstructor(null, TEST_PERSON1_NAME.toUpperCase(), TEST_PERSON2_FIRST_NAME, null,
		null, null, null, null, null, null, null);
	example = Example.of(person, ExampleMatcher.matchingAny().withIgnoreCase("name"));

	persons = repository.findAll(example);
	assertThat(persons).containsExactlyInAnyOrder(person1, person2);

	person = new PersonWithAllConstructor(null,
		TEST_PERSON2_NAME.substring(TEST_PERSON2_NAME.length() - 2).toUpperCase(),
		TEST_PERSON2_FIRST_NAME.substring(0, 2), TEST_PERSON_SAMEVALUE.substring(3, 5), null, null, null, null,
		null, null, null);
	example = Example.of(person, ExampleMatcher
		.matchingAll()
		.withMatcher("name", ExampleMatcher.GenericPropertyMatcher.of(StringMatcher.ENDING, true))
		.withMatcher("firstName", ExampleMatcher.GenericPropertyMatcher.of(StringMatcher.STARTING))
		.withMatcher("sameValue", ExampleMatcher.GenericPropertyMatcher.of(StringMatcher.CONTAINING))
	);

	persons = repository.findAll(example);
	assertThat(persons).containsExactlyInAnyOrder(person2);

	person = new PersonWithAllConstructor(null, null, "(?i)ern.*", null, null, null, null, null, null, null,
		null);
	example = Example.of(person, ExampleMatcher.matchingAll().withStringMatcher(StringMatcher.REGEX));

	persons = repository.findAll(example);
	assertThat(persons).containsExactlyInAnyOrder(person1);

	example = Example
		.of(person,
			ExampleMatcher.matchingAll().withStringMatcher(StringMatcher.REGEX).withIncludeNullValues());

	persons = repository.findAll(example);
	assertThat(persons).isEmpty();
}
 
Example 19
Source File: SysComnLogsService.java    From danyuan-application with Apache License 2.0 3 votes vote down vote up
/**
 * 方法名: findAllZhcx
 * 功 能: TODO(这里用一句话描述这个方法的作用)
 * 参 数: @param vo
 * 参 数: @return
 * 返 回: Page<SysComnLogs>
 * 作 者 : Administrator
 * @throws
 */
public Page<VSysComnLogs> findAllZhcx(SysComnLogsVo vo) {
	Example<VSysComnLogs> example = Example.of(new VSysComnLogs());
	Sort sort = Sort.by(new Order(Direction.DESC, "date1"), new Order(Direction.DESC, "time1"));
	PageRequest request = PageRequest.of(vo.getPageNumber() - 1, vo.getPageSize(), sort);
	Page<VSysComnLogs> sourceCodes = vSysComnLogsDao.findAll(example, request);
	return sourceCodes;
}
 
Example 20
Source File: DeveloperService.java    From heimdall with Apache License 2.0 3 votes vote down vote up
/**
 * Generates a list of {@link Developer} from a request.
 * 
 * @param  developerDTO 			The {@link DeveloperDTO}
 * @return							The list of {@link Developer}
 */
public List<Developer> list(DeveloperDTO developerDTO) {
     
     Developer developer = GenericConverter.mapper(developerDTO, Developer.class);
     
     Example<Developer> example = Example.of(developer, ExampleMatcher.matching().withIgnoreCase().withStringMatcher(StringMatcher.CONTAINING));
     
     List<Developer> developers = developerRepository.findAll(example);
     
     return developers;
}