上节已经生成了Query类,本文通过示例说明如何通过Query类实现灵活查询。
为了说明示例,这里定义简单的User类,以及依据User类生成的QUser类。
User类:
@Document
public class User {
@Id
private String id;
private String name;
private Integer age;
// standard getters and setters
}
QUser类:
Query类是通过gradle插件自动生成的。
/**
* QUser is a Querydsl query type for User
*/
@Generated("com.mysema.query.codegen.EntitySerializer")
public class QUser extends EntityPathBase<User> {
private static final long serialVersionUID = ...;
public static final QUser user = new QUser("user");
public final NumberPath<Integer> age = createNumber("age", Integer.class);
public final StringPath id = createString("id");
public final StringPath name = createString("name");
public QUser(String variable) {
super(User.class, forVariable(variable));
}
public QUser(Path<? extends User> path) {
super(path.getType(), path.getMetadata());
}
public QUser(PathMetadata<?> metadata) {
super(User.class, metadata);
}
}
为了启用QueryDsl查询,需要简单继承QueryDslPredicateExecutor接口。
public interface UserRepository extends
MongoRepository<User, String>, QueryDslPredicateExecutor<User>
实现值相等查询。
QUser qUser = new QUser("user");
Predicate predicate = qUser.name.eq("Eric");
List<User> users = (List<User>) userRepository.findAll(predicate);
也可以指定多个条件
Predicate nameAndAgeAre = qUser.name.eq("Foo").and(qUser.age.eq(22));
实现字符串开头或结尾的模糊查询。
QUser qUser = new QUser("user");
Predicate predicate = qUser.name.startsWith("A");
List<User> users = (List<User>) userRepository.findAll(predicate);
字符串结尾查询:
QUser qUser = new QUser("user");
Predicate predicate = qUser.name.endsWith("c");
List<User> users = (List<User>) userRepository.findAll(predicate);
实现范围查询
QUser qUser = new QUser("user");
Predicate predicate = qUser.age.between(20, 50);
List<User> users = (List<User>) userRepository.findAll(predicate);
实现多个或组条件组合查询,摘录项目中的示例代码如下:
QUser qUser = new QUser("user");
Predicate userCode = qUser.userCode.endsWith("4");
Predicate userName = qUser.userName.endsWith("9").or(qUser.userName.endsWith("8"));
BooleanBuilder example = new BooleanBuilder();
example.and(userCode).or(userName);
List<SysOrg> orgList = (List<SysOrg>)orgDao.findAll(example);
assertThat(orgList,hasSize(3));
QSysOrg qSysOrg;
qSysOrg = new QSysOrg("sysOrg");
Predicate predicate = qSysOrg.orgCode.startsWith("tx");
Pageable pageable = PageRequest.of(0,5);
Page<SysOrg> orgList = orgDao.findAll(predicate,pageable);
assertThat(orgList.hasNext(),is(true));
assertThat(orgList.getSize(),is(5));
QSysOrg qSysOrg = QSysOrg.sysOrg;
Predicate predicate = qSysOrg.orgCode.startsWith("tx");
OrderSpecifier orderSpecifier = qSysOrg.orgCode.asc();
List<SysOrg> orgList = (List<SysOrg>)orgDao.findAll(predicate,orderSpecifier);
SysOrg org = (SysOrg) orgList.get(0);
assertThat(org.getOrgCode(),is("tx001"));
除了上述方法,还有很多功能强大的方法,如:like,contain等,留给善于探索的读者。