public Address validateAddress(AddressDTO addressDTO) { Address addressToSearch = new Address(addressDTO.getCountry(), addressDTO.getCity(), addressDTO.getPostcode(), addressDTO.getStreet(), addressDTO.getStreetNumber()); //@formatter:off ExampleMatcher matcher = ExampleMatcher.matching() .withMatcher("country", startsWith().ignoreCase()) .withMatcher("postcode", startsWith().ignoreCase()) .withMatcher("street", contains().ignoreCase()) .withMatcher("streetNumber", contains().ignoreCase()) .withMatcher("city", contains().ignoreCase()); //@formatter:on Example<Address> searchExample = Example.of(addressToSearch, matcher); return addressRepository.findOne(searchExample); }
/** * Saves a collection of posts. * * @param posts A list of posts. */ protected void savePosts(List<Post> posts) { int inserted = 0; for (Post p : posts) { ExampleMatcher matcher = ExampleMatcher.matching() .withMatcher("url", ExampleMatcher.GenericPropertyMatchers.exact()); if (!postRepository.exists(Example.of(p, matcher))) { logger.info("Inserting " + p.getUrl()); savePost(p); inserted++; } else { logger.info("Duplicate post. Not inserted " + p.getUrl()); } } logger.info("Inserted " + inserted + " items"); }
@Test public void testFindByExample() { User u = new User(); u.setEmailAddress("YUANXUEGUI"); List<User> result1 = repository.findAll(Example.of(u, ExampleMatcher.matchingAll() .withIgnoreCase(true) .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING))); assertEquals(1, result1.size()); assertEquals("Yuan", result1.get(0).getFullName().getLastName()); assertThat(result1, hasItem(user)); List<User> result2 = repository.findAll(Example.of(u, ExampleMatcher.matchingAll() .withIgnoreCase(false) .withStringMatcher(ExampleMatcher.StringMatcher.EXACT))); assertEquals(0, result2.size()); }
@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); }
@Transactional(readOnly = true) public PageResponse<RoleDTO> findAll(PageRequestByExample<RoleDTO> req) { Example<Role> example = null; Role role = toEntity(req.example); if (role != null) { ExampleMatcher matcher = ExampleMatcher.matching() // .withMatcher(Role_.roleName.getName(), match -> match.ignoreCase().startsWith()); example = Example.of(role, matcher); } Page<Role> page; if (example != null) { page = roleRepository.findAll(example, req.toPageable()); } else { page = roleRepository.findAll(req.toPageable()); } List<RoleDTO> content = page.getContent().stream().map(this::toDTO).collect(Collectors.toList()); return new PageResponse<>(page.getTotalPages(), page.getTotalElements(), content); }
@Transactional(readOnly = true) public PageResponse<PassportDTO> findAll(PageRequestByExample<PassportDTO> req) { Example<Passport> example = null; Passport passport = toEntity(req.example); if (passport != null) { ExampleMatcher matcher = ExampleMatcher.matching() // .withMatcher(Passport_.passportNumber.getName(), match -> match.ignoreCase().startsWith()); example = Example.of(passport, matcher); } Page<Passport> page; if (example != null) { page = passportRepository.findAll(example, req.toPageable()); } else { page = passportRepository.findAll(req.toPageable()); } List<PassportDTO> content = page.getContent().stream().map(this::toDTO).collect(Collectors.toList()); return new PageResponse<>(page.getTotalPages(), page.getTotalElements(), content); }
@Transactional(readOnly = true) public PageResponse<UseCase3DTO> findAll(PageRequestByExample<UseCase3DTO> req) { Example<UseCase3> example = null; UseCase3 useCase3 = toEntity(req.example); if (useCase3 != null) { ExampleMatcher matcher = ExampleMatcher.matching() // .withMatcher(UseCase3_.dummy.getName(), match -> match.ignoreCase().startsWith()); example = Example.of(useCase3, matcher); } Page<UseCase3> page; if (example != null) { page = useCase3Repository.findAll(example, req.toPageable()); } else { page = useCase3Repository.findAll(req.toPageable()); } List<UseCase3DTO> content = page.getContent().stream().map(this::toDTO).collect(Collectors.toList()); return new PageResponse<>(page.getTotalPages(), page.getTotalElements(), content); }
@Transactional(readOnly = true) public PageResponse<UserDTO> findAll(PageRequestByExample<UserDTO> req) { Example<User> example = null; User user = toEntity(req.example); if (user != null) { ExampleMatcher matcher = ExampleMatcher.matching() // .withMatcher(User_.login.getName(), match -> match.ignoreCase().startsWith()) .withMatcher(User_.email.getName(), match -> match.ignoreCase().startsWith()) .withMatcher(User_.firstName.getName(), match -> match.ignoreCase().startsWith()) .withMatcher(User_.lastName.getName(), match -> match.ignoreCase().startsWith()); example = Example.of(user, matcher); } Page<User> page; if (example != null) { page = userRepository.findAll(example, req.toPageable()); } else { page = userRepository.findAll(req.toPageable()); } List<UserDTO> content = page.getContent().stream().map(this::toDTO).collect(Collectors.toList()); return new PageResponse<>(page.getTotalPages(), page.getTotalElements(), content); }
@Transactional(readOnly = true) public PageResponse<AuthorDTO> findAll(PageRequestByExample<AuthorDTO> req) { Example<Author> example = null; Author author = toEntity(req.example); if (author != null) { ExampleMatcher matcher = ExampleMatcher.matching() // .withMatcher(Author_.lastName.getName(), match -> match.ignoreCase().startsWith()) .withMatcher(Author_.firstName.getName(), match -> match.ignoreCase().startsWith()) .withMatcher(Author_.email.getName(), match -> match.ignoreCase().startsWith()); example = Example.of(author, matcher); } Page<Author> page; if (example != null) { page = authorRepository.findAll(example, req.toPageable()); } else { page = authorRepository.findAll(req.toPageable()); } List<AuthorDTO> content = page.getContent().stream().map(this::toDTO).collect(Collectors.toList()); return new PageResponse<>(page.getTotalPages(), page.getTotalElements(), content); }
@Transactional(readOnly = true) public PageResponse<ProjectDTO> findAll(PageRequestByExample<ProjectDTO> req) { Example<Project> example = null; Project project = toEntity(req.example); if (project != null) { ExampleMatcher matcher = ExampleMatcher.matching() // .withMatcher(Project_.name.getName(), match -> match.ignoreCase().startsWith()) .withMatcher(Project_.url.getName(), match -> match.ignoreCase().startsWith()); example = Example.of(project, matcher); } Page<Project> page; if (example != null) { page = projectRepository.findAll(example, req.toPageable()); } else { page = projectRepository.findAll(req.toPageable()); } List<ProjectDTO> content = page.getContent().stream().map(this::toDTO).collect(Collectors.toList()); return new PageResponse<>(page.getTotalPages(), page.getTotalElements(), content); }
@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); }
@Transactional(readOnly = true) public PageResponse<BookDTO> findAll(PageRequestByExample<BookDTO> req) { Example<Book> example = null; Book book = toEntity(req.example); if (book != null) { ExampleMatcher matcher = ExampleMatcher.matching() // .withMatcher(Book_.title.getName(), match -> match.ignoreCase().startsWith()) .withMatcher(Book_.summary.getName(), match -> match.ignoreCase().startsWith()); example = Example.of(book, matcher); } Page<Book> page; if (example != null) { page = bookRepository.findAll(example, req.toPageable()); } else { page = bookRepository.findAll(req.toPageable()); } List<BookDTO> content = page.getContent().stream().map(this::toDTO).collect(Collectors.toList()); return new PageResponse<>(page.getTotalPages(), page.getTotalElements(), content); }
@Test public void testMultiple() { // tag::example-flux[] 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); // end::example-flux[] // tag::query-flux[] Flux<Employee> multipleEmployees = repository.findAll(example); // end::query-flux[] StepVerifier.create(multipleEmployees.collectList()) .expectNextMatches(employees -> { assertThat(employees).hasSize(2); assertThat(employees).extracting("firstName") .contains("Frodo", "Bilbo"); return true; }) .expectComplete() .verify(); }
@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(); }
@Test public void testFindByFoodNameWithExampleMatchers(){ ExampleMatcher matcher = ExampleMatcher.matching() .withIgnorePaths("id") .withIgnorePaths("transactionDate"); Example<Eats> example = Example.of(eat, matcher); List<Eats> response = eatsRepository.findByFoodName(testFood); Eats responseExample = Example.of(response.get(0), matcher).getProbe(); log.info("response: " + responseExample.toString()); log.info("repo: " + eatsRepository.findOne(example)); assert(eatsRepository.findOne(example).equals(responseExample)); }
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(); }
default List<Book> complete(String query, int maxResults) { Book probe = new Book(); probe.setTitle(query); ExampleMatcher matcher = ExampleMatcher.matching() // .withMatcher(Book_.title.getName(), match -> match.ignoreCase().startsWith()); Page<Book> page = findAll(Example.of(probe, matcher), new PageRequest(0, maxResults)); return page.getContent(); }
default List<UseCase3> complete(String query, int maxResults) { UseCase3 probe = new UseCase3(); probe.setDummy(query); ExampleMatcher matcher = ExampleMatcher.matching() // .withMatcher(UseCase3_.dummy.getName(), match -> match.ignoreCase().startsWith()); Page<UseCase3> page = findAll(Example.of(probe, matcher), new PageRequest(0, maxResults)); return page.getContent(); }
default List<UseCase2> complete(String query, int maxResults) { UseCase2 probe = new UseCase2(); probe.setDummy(query); ExampleMatcher matcher = ExampleMatcher.matching() // .withMatcher(UseCase2_.dummy.getName(), match -> match.ignoreCase().startsWith()); Page<UseCase2> page = findAll(Example.of(probe, matcher), new PageRequest(0, maxResults)); return page.getContent(); }
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(); }
default List<Author> complete(String query, int maxResults) { Author probe = new Author(); probe.setLastName(query); ExampleMatcher matcher = ExampleMatcher.matching() // .withMatcher(Author_.lastName.getName(), match -> match.ignoreCase().startsWith()); Page<Author> page = findAll(Example.of(probe, matcher), new PageRequest(0, maxResults)); return page.getContent(); }
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(); }
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(); }
default List<Project> complete(String query, int maxResults) { Project probe = new Project(); probe.setName(query); ExampleMatcher matcher = ExampleMatcher.matching() // .withMatcher(Project_.name.getName(), match -> match.ignoreCase().startsWith()); Page<Project> page = findAll(Example.of(probe, matcher), new PageRequest(0, maxResults)); return page.getContent(); }
@Test public void shouldUseExample() { Company template = Company.builder().name("javatech").address(Address.builder().city("radom").street("koncowa").build()).build(); ExampleMatcher matcher = ExampleMatcher.matching().withIgnorePaths("depts").withIncludeNullValues(); //<2> Example<Company> example = Example.of(template,matcher); companyRepo.findAll(example); }
@GetMapping public PagedResources<Resource<SecondaryModel>> getSecondary(Pageable pageable, SecondaryModel secondaryModel) { ExampleMatcher exampleMatcher = ExampleMatcher.matching() .withMatcher("name", matcher -> matcher.stringMatcher(CONTAINING)) .withIgnoreCase() .withIgnoreNullValues(); Example<SecondaryModel> example = Example.of(secondaryModel, exampleMatcher); return pagedAssembler.toResource(secondaryRepository.findAll(example, pageable)); }
@GetMapping public PagedResources<Resource<PrimaryModel>> getPrimary(Pageable pageable, PrimaryModel primaryModel) { ExampleMatcher exampleMatcher = ExampleMatcher.matching() .withMatcher("name", matcher -> matcher.stringMatcher(CONTAINING)) .withIgnoreCase() .withIgnoreNullValues(); Example<PrimaryModel> example = Example.of(primaryModel, exampleMatcher); return pagedAssembler.toResource(primaryRepository.findAll(example, pageable)); }
static void getPredicates(Query<?> q, String path, ITableMetadata type, Object value, Class<?> probeType, ExampleMatcherAccessor exampleAccessor, PathNode currentNode) { // List<Predicate> predicates = new ArrayList<Predicate>(); DirectFieldAccessFallbackBeanWrapper beanWrapper = new DirectFieldAccessFallbackBeanWrapper(value); for (ColumnMapping attribute : type.getColumns()) { String fieldName = attribute.fieldName(); String currentPath = !StringUtils.hasText(path) ? fieldName : path + "." + fieldName; if (exampleAccessor.isIgnoredPath(currentPath)) { continue; } Object attributeValue = exampleAccessor.getValueTransformerForPath(currentPath).convert(beanWrapper.getPropertyValue(fieldName)); if (attributeValue == null) { if (exampleAccessor.getNullHandler().equals(ExampleMatcher.NullHandler.INCLUDE)) { q.addCondition(QB.isNull(type.getField(fieldName))); } continue; } // 这种情况不存在 // if // (attribute.getPersistentAttributeType().equals(PersistentAttributeType.EMBEDDED)) // { // // predicates.addAll(getPredicates(currentPath, cb, // from.get(attribute.getName()), // (ManagedType<?>) attribute.getType(), attributeValue, probeType, // exampleAccessor, currentNode)); // continue; // } Field expression = attribute.field(); if (attribute.getFieldType().equals(String.class)) { // 全转小写处理 if (exampleAccessor.isIgnoreCaseForPath(currentPath)) { expression = new FBIField("lower(" + expression.name() + ")", q); attributeValue = attributeValue.toString().toLowerCase(); } // 根据运算符计算String的运算符 switch (exampleAccessor.getStringMatcherForPath(currentPath)) { case DEFAULT: case EXACT: q.addCondition(QB.eq(expression, attributeValue)); break; case CONTAINING: q.addCondition(QB.matchAny(expression, String.valueOf(attributeValue))); break; case STARTING: q.addCondition(QB.matchStart(expression, String.valueOf(attributeValue))); break; case ENDING: q.addCondition(QB.matchEnd(expression, String.valueOf(attributeValue))); break; default: throw new IllegalArgumentException("Unsupported StringMatcher " + exampleAccessor.getStringMatcherForPath(currentPath)); } } else { q.addCondition(QB.eq(expression, attributeValue)); } } // 处理位于引用字段(关系对象)上的条件,先不支持,后续再加 // if (isAssociation(attribute)) { // // if (!(from instanceof From)) { // throw new JpaSystemException(new IllegalArgumentException( // String.format("Unexpected path type for %s. Found % where From.class was expected.", // currentPath, from))); // } // // PathNode node = currentNode.add(attribute.getName(), attributeValue); // if (node.spansCycle()) { // throw new InvalidDataAccessApiUsageException( // String.format("Path '%s' from root %s must not span a cyclic property reference!\r\n%s", // currentPath, // ClassUtils.getShortName(probeType), node)); // } // // predicates.addAll(getPredicates(currentPath, cb, ((From<?, ?>) // from).join(attribute.getName()), // (ManagedType<?>) attribute.getType(), attributeValue, probeType, // exampleAccessor, node)); }
/** * create an example filter with a custom matcher * * @param probe Probe to filter by * @param exampleMatcher example matcher to use */ public ExampleFilter(T probe, ExampleMatcher exampleMatcher) { example = Example.of(probe, exampleMatcher); }
/** * create an example filter with the default matcher (ignore case and match strings with CONTAINING) * * @param probe Probe to filter by */ public ExampleFilter(T probe) { this(probe, ExampleMatcher.matching().withIgnoreCase().withStringMatcher(StringMatcher.CONTAINING)); }