// select userentity0_.id as id1_0_, userentity0_.email as email2_0_, userentity0_.name as name3_0_ from user userentity0_ where userentity0_.name=? and userentity0_.id=0
UserEntity userEntity = new UserEntity();
userEntity.setName("admin");
Example<UserEntity> example = Example.of(userEntity);
List<UserEntity> list = userRepository.findAll(example);
以findAll方法为例,可接收Example对象
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.QueryByExampleExecutor#findAll(org.springframework.data.domain.Example)
*/
@Override
<S extends T> List<S> findAll(Example<S> example);
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.QueryByExampleExecutor#findAll(org.springframework.data.domain.Example, org.springframework.data.domain.Sort)
*/
@Override
<S extends T> List<S> findAll(Example<S> example, Sort sort);
Example接口结构如下,可使用of方法获取实例
of(T probe) 等同于 of(T probe, ExampleMatcher.matching())
/**
* Create a new {@link Example} including all non-null properties by default.
*
* @param probe must not be {@literal null}.
* @return
*/
static <T> Example<T> of(T probe) {
return new TypedExample<>(probe, ExampleMatcher.matching());
}
/**
* Create a new {@link Example} using the given {@link ExampleMatcher}.
*
* @param probe must not be {@literal null}.
* @param matcher must not be {@literal null}.
* @return
*/
static <T> Example<T> of(T probe, ExampleMatcher matcher) {
return new TypedExample<>(probe, matcher);
}
ExampleMatcher接口结构如下
示例
// select userentity0_.id as id1_0_, userentity0_.email as email2_0_, userentity0_.name as name3_0_ from user userentity0_ where userentity0_.id=1
UserEntity userEntity = new UserEntity();
userEntity.setId(1);
Example<UserEntity> example = Example.of(userEntity);
List<UserEntity> list = userRepository.findAll(example);
ExampleMatcher.matching() 创建一个新的ExampleMatcher,默认情况下包含所有非NULL属性,以匹配从该示例派生的所有谓词。由于UserEntity中id初始值为0,不为NULL,所以下方示例中会有id字段的查询
// select userentity0_.id as id1_0_, userentity0_.email as email2_0_, userentity0_.name as name3_0_ from user userentity0_ where userentity0_.name=? and userentity0_.id=0
UserEntity userEntity = new UserEntity();
userEntity.setName("admin");
Example<UserEntity> example = Example.of(userEntity);
List<UserEntity> list = userRepository.findAll(example);
可以使用ExampleMatcher指定不参与查询的字段
// select userentity0_.id as id1_0_, userentity0_.email as email2_0_, userentity0_.name as name3_0_ from user userentity0_ where userentity0_.name=?
UserEntity userEntity = new UserEntity();
userEntity.setName("admin");
ExampleMatcher exampleMatcher = ExampleMatcher.matching().withIgnorePaths("id");
Example<UserEntity> example = Example.of(userEntity,exampleMatcher);
List<UserEntity> list = userRepository.findAll(example);
可以使用ExampleMatcher的其他方法来实现稍微复杂的查询