下面列出了org.springframework.data.domain.ExampleMatcher.StringMatcher#org.springframework.data.domain.ExampleMatcher 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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));
}
@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());
}
@Test
public void endingWithByExampleNestedTest() {
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", null, 66);
nested3.setNestedCustomer(nested2);
exampleCustomer.setNestedCustomer(nested3);
final Example<Customer> example = Example.of(exampleCustomer,
ExampleMatcher.matching().withMatcher("nestedCustomer.name", match -> match.endsWith())
.withIgnoreCase("nestedCustomer.name").withIgnoreNullValues()
.withTransformer("nestedCustomer.age", o -> Optional.of(Integer.valueOf(o.get().toString()) + 1)));
final Customer retrieved = repository.findOne(example).get();
assertEquals(check, retrieved);
}
@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);
}
@Test
public void exampleWithRefPropertyTest() {
ShoppingCart shoppingCart = new ShoppingCart();
shoppingCartRepository.save(shoppingCart);
Customer customer = new Customer("Dhiren", "Upadhyay", 28);
customer.setShoppingCart(shoppingCart);
repository.save(customer);
Customer customer1 = new Customer();
customer1.setShoppingCart(shoppingCart);
ExampleMatcher exampleMatcher = ExampleMatcher.matching().withIgnorePaths("age", "location", "alive");
Example<Customer> example = Example.of(customer1, exampleMatcher);
final Customer retrieved = repository.findOne(example).orElse(null);
assertEquals(customer, retrieved);
}
private <T> void validateExample(Example<T> example) {
Assert.notNull(example, "A non-null example is expected");
ExampleMatcher matcher = example.getMatcher();
if (!matcher.isAllMatching()) {
throw new DatastoreDataException("Unsupported MatchMode. Only MatchMode.ALL is supported");
}
if (matcher.isIgnoreCaseEnabled()) {
throw new DatastoreDataException("Ignore case matching is not supported");
}
if (!(matcher.getDefaultStringMatcher() == ExampleMatcher.StringMatcher.EXACT
|| matcher.getDefaultStringMatcher() == ExampleMatcher.StringMatcher.DEFAULT)) {
throw new DatastoreDataException("Unsupported StringMatcher. Only EXACT and DEFAULT are supported");
}
Optional<String> path =
example.getMatcher().getIgnoredPaths().stream().filter((s) -> s.contains(".")).findFirst();
if (path.isPresent()) {
throw new DatastoreDataException("Ignored paths deeper than 1 are not supported");
}
if (matcher.getPropertySpecifiers().hasValues()) {
throw new DatastoreDataException("Property matchers are not supported");
}
}
@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)));
}
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);
}
@Test
public void testExample() {
UserEntity admin = new UserEntity();
admin.setUserName("example");
admin.setLoginName("example");
admin.setPassword(BCryptPassWordUtils.encode("example"));
admin.setEmail("[email protected]");
ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("userName", endsWith())
.withMatcher("loginName", startsWith().ignoreCase());
Example<UserEntity> example = Example.of(admin, matcher);
MyFastJsonUtils.prettyPrint(userRepository.findAll(example));
System.out.println(userRepository.count(example));
}
@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<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);
}
private void add(ExampleMatcher.MatchMode matchMode, Condition additionalCondition) {
switch (matchMode) {
case ALL:
this.condition = this.condition.and(additionalCondition);
break;
case ANY:
this.condition = this.condition.or(additionalCondition);
break;
default:
throw new IllegalArgumentException("Unsupported match mode: " + matchMode);
}
}
@Test
void findOneByExample(@Autowired PersonRepository repository) {
Example<PersonWithAllConstructor> example = Example
.of(person1, ExampleMatcher.matchingAll().withIgnoreNullValues());
Optional<PersonWithAllConstructor> person = repository.findOne(example);
assertThat(person).isPresent();
assertThat(person.get()).isEqualTo(person1);
}
@Test
void findAllByExample(@Autowired PersonRepository repository) {
Example<PersonWithAllConstructor> example = Example
.of(person1, ExampleMatcher.matchingAll().withIgnoreNullValues());
List<PersonWithAllConstructor> persons = repository.findAll(example);
assertThat(persons).containsExactly(person1);
}
@Test
void findOneByExample(@Autowired ReactivePersonRepository repository) {
Example<PersonWithAllConstructor> example = Example.of(person1,
ExampleMatcher.matchingAll().withIgnoreNullValues());
StepVerifier.create(repository.findOne(example)).expectNext(person1).verifyComplete();
}
@Test
public void findAllByExampleAndSort() {
User user = new User();
user.setName("xiaoliu");
user.setAddress("beij");
user.setAge(8);
ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("name", ExampleMatcher.GenericPropertyMatchers.startsWith())//模糊查询匹配开头,即{username}%
.withMatcher("address" ,ExampleMatcher.GenericPropertyMatchers.contains())//全部模糊查询,即%{address}%
.withIgnorePaths("id")//忽略字段,即不管id是什么值都不加入查询条件
.withIgnorePaths("age");//忽略字段,即不管id是什么值都不加入查询条件
Example<User> example = Example.of(user ,matcher);
List<User> userList = userJpaRepository.findAll(example,new Sort(Sort.Direction.ASC, "age"));
Assert.assertTrue(userList.size() > 0);
}
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<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();
}
private Example<Operation> prepareExample(Long apiId, Long resourceId, OperationDTO operationDTO) {
Resource resource = resourceRepository.findByApiIdAndId(apiId, resourceId);
HeimdallException.checkThrow(resource == null, GLOBAL_RESOURCE_NOT_FOUND);
Operation operation = GenericConverter.mapper(operationDTO, Operation.class);
operation.setResource(resource);
return Example.of(operation, ExampleMatcher.matching().withIgnorePaths("resource.api").withIgnoreCase().withStringMatcher(StringMatcher.CONTAINING));
}
private Example<Middleware> createExample(Long apiId, MiddlewareDTO middlewareDTO) {
Api api = apiRepository.findOne(apiId);
HeimdallException.checkThrow(api == null, GLOBAL_RESOURCE_NOT_FOUND);
Middleware middleware = GenericConverter.mapper(middlewareDTO, Middleware.class);
Api apiFind = new Api();
apiFind.setId(apiId);
middleware.setApi(apiFind);
return Example.of(middleware, ExampleMatcher.matching().withIgnoreCase().withStringMatcher(StringMatcher.CONTAINING));
}
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();
}
@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();
}
/**
* 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);
}
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();
}