Querydsl是jpa的擴展
(一)引入Querydsl的相關依賴和插件
<dependency> <groupId>com.querydsl</groupId> <artifactId>querydsl-apt</artifactId> <version>${querydsl.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.querydsl</groupId> <artifactId>querydsl-jpa</artifactId> <version>${querydsl.version}</version> </dependency>
<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>
(二)定義enetity(@Data在文末有說明)
@Entity @Table(name = "school") @Data @ToString public class School { @Id private Long id; private String name; private Integer age; private String title; }
(三)定義Repository
public interface SchoolRepository extends QueryDslPredicateExecutor<School> { }
(四)查詢
我們先用spring data jpa官網給的使用方法
首先讓我們自己的Repository繼承QueryDslPredicateExecutor
public interface AuthorDslRepository extends JpaRepository<Author,Long>,QueryDslPredicateExecutor<Author>{ }
看下QueryDslPredicateExecutor接口,我們會看到這么幾個定義好的類。
public interface QueryDslPredicateExecutor<T> { T findOne(Predicate var1); Iterable<T> findAll(Predicate var1); Iterable<T> findAll(Predicate var1, Sort var2); Iterable<T> findAll(Predicate var1, OrderSpecifier... var2); Iterable<T> findAll(OrderSpecifier... var1); Page<T> findAll(Predicate var1, Pageable var2); long count(Predicate var1); boolean exists(Predicate var1); }
查詢是通過JPAQuery實例來實現的。
下面看個使用案例
@RequestMapping("/dslTest") public String dslTest(){ QSchool qSchool = QSchool.school; JPAQuery jpaQuery = new JPAQuery(entityManager); return jpaQuery.select(qSchool).from(qSchool).fetch().toString(); }
不過querydsl官方推薦JPAQuery的實例的獲取方式最好是通過JPAQueryFactory的方式獲取(JPAQueryFactory
should be the preferred option to obtain JPAQuery
instances.)
下面看下使用JPAQueryFactory的案例
@RequestMapping("/factoryTest") public String factoryTest(){ QSchool qSchool = QSchool.school; JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager); return queryFactory.selectFrom(qSchool).fetch().toString(); }
這邊我們用的是selectFrom,其實就是上面的select().from()。
我們看下JPAQueryFactory的selectFrom()方法就明白了。
public <T> JPAQuery<T> selectFrom(EntityPath<T> from) { return (JPAQuery)this.select((Expression)from).from(from); }
加入查詢條件
@RequestMapping("/whereTest") public String whereTest(){ QSchool qSchool = QSchool.school; JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager); List<School> schools = queryFactory.selectFrom(qSchool).where(qSchool.age.eq(74).or(qSchool.title.eq("sfd"))).fetch(); List<School> schoolList = queryFactory.selectFrom(qSchool).where(qSchool.age.eq(74).and(qSchool.id.eq(1l))).fetch(); List<School> list = new ArrayList<>(); list.addAll(schoolList); list.addAll(schools); return list.toString(); }
關於其他的一些的用法可以直接看官網給的這段描述
2.1.8. General usage
Use the the cascading methods of the JPQLQuery interface like this
select: Set the projection of the query. (Not necessary if created via query factory)
from: Add the query sources here.
innerJoin, join, leftJoin, rightJoin, on: Add join elements using these constructs. For the join methods the first argument is the join source and the second the target (alias).
where: Add query filters, either in varargs form separated via commas or cascaded via the and-operator.
groupBy: Add group by arguments in varargs form.
having: Add having filters of the "group by" grouping as an varags array of Predicate expressions.
orderBy: Add ordering of the result as an varargs array of order expressions. Use asc() and desc() on numeric, string and other comparable expression to access the OrderSpecifier instances.
limit, offset, restrict: Set the paging of the result. Limit for max results, offset for skipping rows and restrict for defining both in one call.
關於@Data是使用了lombok,關於lombok,下面會寫一篇簡單介紹下使用方法。