- 第一步, 生成查询对象
在一个jpa项目中加入如下依赖和配置:
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<scope>provided</scope>
</dependency>
<build>
<plugins>
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
如果报找不到Inject类还需要加入:
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
然后去命令行运行mvn clean compile (IDEA的compile好像不行), 插件会扫描@Entity对象并且按名称生成查询对象, 例如@Entity class Country会生成class QCountry类, 代码在指定的outputDirectory里
将生成的查询对象移动到项目里
repository继承QueryDslPredicateExecutor<T>
public interface CountryRepository extends JpaRepository<Country, String>, QueryDslPredicateExecutor<Country> {
}
下边是一个条件查询的例子, 使用了Pageable
private Page<Country> searchByContinent(String continent, Pageable pageable) {
BooleanBuilder booleanBuilder = new BooleanBuilder();
if (hasLength(continent)) {
booleanBuilder.and(QCountry.country.continent.eq(continent));
}
return countryRepository.findAll(booleanBuilder.getValue(), pageable);
}