SpringDataJPA+QueryDSL玩轉態動條件/投影查詢


  在本文之前,本應當專門有一篇博客講解SpringDataJPA使用自帶的Specification+JpaSpecificationExecutor去說明如何玩條件查詢,但是看到新奇、編碼更簡單易懂的技術總是會讓人感到驚喜,而且QueryDSL對SpringDataJPA有着完美的支持。如果你沒有使用過自帶的Specification去做復雜查詢,不用擔心,本節分享的QueryDSL技術與SpringDataJPA自帶支持的Specification沒有關聯。注意,本文內容一切都是基於SpringBoot1.x上構建的,如果還沒有使用過SpringBoot的伙伴,請移步SpringBoot進行初步入門。

 

1、QueryDSL簡介

  如果說Hibernate等ORM是JPA的實現,而SpringDataJPA是對JPA使用的封裝,那么QueryDSL可以是與SpringDataJPA有着同階層的級別,它也是基於各種ORM之上的一個通用查詢框架,使用它的API類庫可以寫出“Java代碼的sql”,不用去手動接觸sql語句,表達含義卻如sql般准確。更重要的一點,它能夠構建類型安全的查詢,這比起JPA使用原生查詢時有很大的不同,我們可以不必再對惡心的“Object[]”進行操作了。當然,我們可以SpringDataJPA + QueryDSL JPA聯合使用,它們之間有着完美的相互支持,以達到更高效的編碼。

2、QueryDSL JPA的使用

2.1 編寫配置

2.1.1 pom.xml配置

在maven pom.xml的plugins標簽中配置以下plugin:


   
   
  
  
          
  1. <build>
  2. <plugins>
  3. <!--其他plugin...........-->
  4. <!--因為是類型安全的,所以還需要加上Maven APT plugin,使用 APT 自動生成一些類:-->
  5. <plugin>
  6. <groupId>com.mysema.maven </groupId>
  7. <artifactId>apt-maven-plugin </artifactId>
  8. <version>1.1.3 </version>
  9. <executions>
  10. <execution>
  11. <phase>generate-sources </phase>
  12. <goals>
  13. <goal>process </goal>
  14. </goals>
  15. <configuration>
  16. <outputDirectory>target/generated-sources </outputDirectory>
  17. <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor </processor>
  18. </configuration>
  19. </execution>
  20. </executions>
  21. </plugin>
  22. </plugins>
  23. </build>

繼續在pom.xml 的dependencies中配置以下依賴:


   
   
  
  
          
  1. <dependencies>
  2. <!--SpringDataJPA-->
  3. <dependency>
  4. <groupId>org.springframework.boot </groupId>
  5. <artifactId>spring-boot-starter-data-jpa </artifactId>
  6. </dependency>
  7. <!--Web支持-->
  8. <dependency>
  9. <groupId>org.springframework.boot </groupId>
  10. <artifactId>spring-boot-starter-web </artifactId>
  11. </dependency>
  12. <!--QueryDSL支持-->
  13. <dependency>
  14. <groupId>com.querydsl </groupId>
  15. <artifactId>querydsl-apt </artifactId>
  16. <scope>provided </scope>
  17. </dependency>
  18. <!--QueryDSL支持-->
  19. <dependency>
  20. <groupId>com.querydsl </groupId>
  21. <artifactId>querydsl-jpa </artifactId>
  22. </dependency>
  23. <!--mysql驅動-->
  24. <dependency>
  25. <groupId>mysql </groupId>
  26. <artifactId>mysql-connector-java </artifactId>
  27. <scope>runtime </scope>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot </groupId>
  31. <artifactId>spring-boot-starter-test </artifactId>
  32. <scope>test </scope>
  33. </dependency>
  34. <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
  35. <dependency>
  36. <groupId>org.projectlombok </groupId>
  37. <artifactId>lombok </artifactId>
  38. <version>1.16.10 </version>
  39. <scope>provided </scope>
  40. </dependency>
  41. </dependencies>

2.1.2 application.properties配置

application.properties與之前幾篇SpringDataJPA文章的application.yml配置作用是相同的,配置如下:


   
   
  
  
          
  1. server.port= 8888
  2. server.context-path=/
  3. server.tomcat.uri-encoding=utf -8
  4. #數據源配置
  5. spring.datasource.url=jdbc:mysql: //127.0.0.1:3306/springboot_test?characterEncoding=utf8
  6. #數據庫賬號
  7. spring.datasource.username=root
  8. #數據庫密碼
  9. spring.datasource.password=
  10. spring.jpa.database=mysql
  11. #是否展示sql
  12. spring.jpa.show-sql= true
  13. #是否自動生/更新成表,根據什么策略
  14. spring.jpa.hibernate.ddl-auto=update
  15. #命名策略,會將Java代碼中的駝峰命名法映射到數據庫中會變成下划線法
  16. spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy

2.1.3 JPAQueryFactory配置

使用QueryDSL的功能時,會依賴使用到JPAQueryFactory,而JPAQueryFactory在這里依賴使用EntityManager,所以在主類中做如下配置,使得Spring自動幫我們注入EntityManager與自動管理JPAQueryFactory:


   
   
  
  
          
  1. @SpringBootApplication
  2. public class App {
  3. public static void main(String[] args) {
  4. SpringApplication.run(App.class, args);
  5. }
  6. //讓Spring管理JPAQueryFactory
  7. @Bean
  8. public JPAQueryFactory jpaQueryFactory(EntityManager entityManager){
  9. return new JPAQueryFactory(entityManager);
  10. }
  11. }

2.1.4 編寫實體建模

在這里我們先介紹單表,待會兒介紹多表時我們在進行關聯Entity的配置


   
   
  
  
          
  1. @Data
  2. @Entity
  3. @Table(name = "t_user")
  4. public class User {
  5. @Id
  6. @GeneratedValue(strategy = GenerationType.IDENTITY)
  7. private Integer userId;
  8. private String username;
  9. private String password;
  10. private String nickName;
  11. private Date birthday;
  12. private BigDecimal uIndex; //排序號
  13. }

這個實體類非常簡單,相信大家一定有所理解。沒有使用過@Data注解,也可以不用,暫且就將他當做可以自動生成getXXX/setXXX方法的工具,如果你沒有使用這個注解,也可以直接使用IDEA快捷鍵進行生成setXXX/getXXX。如果想了解這類注解,請前往lombok介紹

2.1.5 執行maven命令

然后在IDEA中選中你的MavenProject按鈕,選中你的maven項目,雙擊compile按鈕:

如果你的控制台提示你compile執行失敗了,那么請留意一下你的maven路徑是否在IDEA中進行了正確的配置。

以上步驟執行完畢后,會在你的target中自動生成了QUser類:

該類中的代碼大致是這樣的:


   
   
  
  
          
  1. @Generated( "com.querydsl.codegen.EntitySerializer")
  2. public class QUser extends EntityPathBase<User> {
  3. private static final long serialVersionUID = - 646136422L;
  4. public static final QUser user = new QUser( "user");
  5. public final DateTimePath<java.util.Date> birthday = createDateTime( "birthday", java.util.Date.class);
  6. public final StringPath nickName = createString( "nickName");
  7. public final StringPath password = createString( "password");
  8. public final NumberPath<java.math.BigDecimal> uIndex = createNumber( "uIndex", java.math.BigDecimal.class);
  9. public final NumberPath<Integer> userId = createNumber( "userId", Integer.class);
  10. public final StringPath username = createString( "username");
  11. public QUser(String variable) {
  12. super(User.class, forVariable(variable));
  13. }
  14. public QUser(Path<? extends User> path) {
  15. super(path.getType(), path.getMetadata());
  16. }
  17. public QUser(PathMetadata metadata) {
  18. super(User.class, metadata);
  19. }
  20. }

一般每有一個實體Bean配置了@Entity被檢測到之后,就會在target的子目錄中自動生成一個Q+實體名稱 的類,這個類對我們使用QueryDSL非常重要,正是因為它,我們才使得QueryDSL能夠構建類型安全的查詢。

2.2 使用

2.2.1 單表使用

在repository包中添加UserRepository,使用QueryDSL時可以完全不依賴使用QueryDslPredicateExecutor,但是為了展示與SpringDataJPA的聯合使用,我們讓repository繼承這個接口,以便獲得支持:


   
   
  
  
          
  1. public interface UserRepository extends JpaRepository<User, Integer>, QueryDslPredicateExecutor<User> {
  2. }

為了講解部分字段映射查詢,我們在bean包創建一個UserDTO類,該類只有User實體的部分字段:


   
   
  
  
          
  1. @Data
  2. @Builder
  3. public class UserDTO {
  4. private String userId;
  5. private String username;
  6. private String nickname;
  7. private String birthday;
  8. }

對於@Data與@Buider,都是lombok里的注解,能夠幫我們生成get/set、toString方法,還能使用建造者模式去創建UserDTO,如果不會的同學也可以使用IDE生成get/set,想了解的同學可以進入lombok進行簡單學習。

在service包中添加UserService,代碼如下:


   
   
  
  
          
  1. @Service
  2. public class UserService {
  3. @Autowired
  4. private UserRepository userRepository;
  5. @Autowired
  6. JPAQueryFactory jpaQueryFactory;
  7. //////////////////////////以下展示使用原生的dsl/////////////////////
  8. /**
  9. * 根據用戶名和密碼查找(假定只能找出一條)
  10. *
  11. * @param username
  12. * @param password
  13. * @return
  14. */
  15. public User findByUsernameAndPassword(String username, String password) {
  16. QUser user = QUser.user;
  17. return jpaQueryFactory
  18. .selectFrom(user)
  19. .where(
  20. user.username.eq(username),
  21. user.password.eq(password)
  22. )
  23. .fetchOne();
  24. }
  25. /**
  26. * 查詢所有的實體,根據uIndex字段排序
  27. *
  28. * @return
  29. */
  30. public List<User> findAll() {
  31. QUser user = QUser.user;
  32. return jpaQueryFactory
  33. .selectFrom(user)
  34. .orderBy(
  35. user.uIndex.asc()
  36. )
  37. .fetch();
  38. }
  39. /**
  40. *分頁查詢所有的實體,根據uIndex字段排序
  41. *
  42. * @return
  43. */
  44. public QueryResults<User> findAllPage(Pageable pageable) {
  45. QUser user = QUser.user;
  46. return jpaQueryFactory
  47. .selectFrom(user)
  48. .orderBy(
  49. user.uIndex.asc()
  50. )
  51. .offset(pageable.getOffset()) //起始頁
  52. .limit(pageable.getPageSize()) //每頁大小
  53. .fetchResults(); //獲取結果,該結果封裝了實體集合、分頁的信息,需要這些信息直接從該對象里面拿取即可
  54. }
  55. /**
  56. * 根據起始日期與終止日期查詢
  57. * @param start
  58. * @param end
  59. * @return
  60. */
  61. public List<User> findByBirthdayBetween(Date start, Date end){
  62. QUser user = QUser.user;
  63. return jpaQueryFactory
  64. .selectFrom(user)
  65. .where(
  66. user.birthday.between(start, end)
  67. )
  68. .fetch();
  69. }
  70. /**
  71. * 部分字段映射查詢
  72. * 投影為UserRes,lambda方式(靈活,類型可以在lambda中修改)
  73. *
  74. * @return
  75. */
  76. public List<UserDTO> findAllUserDto(Pageable pageable) {
  77. QUser user = QUser.user;
  78. List<UserDTO> dtoList = jpaQueryFactory
  79. .select(
  80. user.username,
  81. user.userId,
  82. user.nickName,
  83. user.birthday
  84. )
  85. .from(user)
  86. .offset(pageable.getOffset())
  87. .limit(pageable.getPageSize())
  88. .fetch()
  89. .stream()
  90. .map(tuple -> UserDTO.builder()
  91. .username(tuple.get(user.username))
  92. .nickname(tuple.get(user.nickName))
  93. .userId(tuple.get(user.userId).toString())
  94. .birthday( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(tuple.get(user.birthday)))
  95. .build()
  96. )
  97. .collect(Collectors.toList());
  98. return dtoList;
  99. }
  100. /**
  101. * 部分字段映射查詢
  102. * 投影為UserRes,自帶的Projections方式,不夠靈活,不能轉換類型,但是可以使用as轉換名字
  103. *
  104. * @return
  105. */
  106. /*public List<UserDTO> findAllDto2() {
  107. QUser user = QUser.user;
  108. List<UserDTO> dtoList = jpaQueryFactory
  109. .select(
  110. Projections.bean(
  111. UserDTO.class,
  112. user.username,
  113. user.userId,
  114. user.nickName,
  115. user.birthday
  116. )
  117. )
  118. .from(user)
  119. .fetch();
  120. return dtoList;
  121. }*/
  122. //////////////////////////以下展示使用與SpringDataJPA整合的dsl/////////////////////
  123. /**
  124. * 根據昵稱與用戶名查詢,並且根據uIndex排序
  125. *
  126. * @param nickName
  127. * @return
  128. */
  129. public List<User> findByNicknameAndUsername(String nickName, String username) {
  130. QUser user = QUser.user;
  131. List<User> users = (List<User>) userRepository.findAll(
  132. user.nickName.eq(nickName)
  133. .and(user.username.eq(username)),
  134. user.uIndex.asc() //排序參數
  135. );
  136. return users;
  137. }
  138. /**
  139. * 統計名字像likeName的記錄數量
  140. *
  141. * @return
  142. */
  143. public long countByNickNameLike(String likeName) {
  144. QUser user = QUser.user;
  145. return userRepository.count(
  146. user.nickName.like( "%" + likeName + "%")
  147. );
  148. }
  149. //////////////////////////展示dsl動態查詢////////////////////////////////
  150. /**
  151. * 所有條件動態分頁查詢
  152. *
  153. * @param username
  154. * @param password
  155. * @param nickName
  156. * @param birthday
  157. * @param uIndex
  158. * @return
  159. */
  160. public Page<User> findByUserProperties(Pageable pageable, String username, String password, String nickName, Date birthday, BigDecimal uIndex) {
  161. QUser user = QUser.user;
  162. //初始化組裝條件(類似where 1=1)
  163. Predicate predicate = user.isNotNull().or(user.isNull());
  164. //執行動態條件拼裝
  165. predicate = username == null ? predicate : ExpressionUtils.and(predicate,user.username.eq(username));
  166. predicate = password == null ? predicate : ExpressionUtils.and(predicate,user.password.eq(password));
  167. predicate = nickName == null ? predicate : ExpressionUtils.and(predicate,user.nickName.eq(username));
  168. predicate = birthday == null ? predicate : ExpressionUtils.and(predicate,user.birthday.eq(birthday));
  169. predicate = uIndex == null ? predicate : ExpressionUtils.and(predicate,user.uIndex.eq(uIndex));
  170. Page<User> page = userRepository.findAll(predicate, pageable);
  171. return page;
  172. }
  173. /**
  174. * 動態條件排序、分組查詢
  175. * @param username
  176. * @param password
  177. * @param nickName
  178. * @param birthday
  179. * @param uIndex
  180. * @return
  181. */
  182. public List<User> findByUserPropertiesGroupByUIndex(String username, String password, String nickName, Date birthday, BigDecimal uIndex) {
  183. QUser user = QUser.user;
  184. //初始化組裝條件(類似where 1=1)
  185. Predicate predicate = user.isNotNull().or(user.isNull());
  186. //執行動態條件拼裝
  187. predicate = username == null ? predicate : ExpressionUtils.and(predicate, user.username.eq(username));
  188. predicate = password == null ? predicate : ExpressionUtils.and(predicate, user.password.eq(password));
  189. predicate = nickName == null ? predicate : ExpressionUtils.and(predicate, user.nickName.eq(username));
  190. predicate = birthday == null ? predicate : ExpressionUtils.and(predicate, user.birthday.eq(birthday));
  191. predicate = uIndex == null ? predicate : ExpressionUtils.and(predicate, user.uIndex.eq(uIndex));
  192. //執行拼裝好的條件並根據userId排序,根據uIndex分組
  193. List<User> list = jpaQueryFactory
  194. .selectFrom(user)
  195. .where(predicate) //執行條件
  196. .orderBy(user.userId.asc()) //執行排序
  197. .groupBy(user.uIndex) //執行分組
  198. .having(user.uIndex.longValue().max().gt( 7)) //uIndex最大值小於7
  199. .fetch();
  200. //封裝成Page返回
  201. return list;
  202. }
  203. }

代碼有點多,解釋一波。

a、第一個方法是根據用戶名與密碼進行查詢,QUser中有一個靜態user屬性,直接生成QUser的實例,QueryDSL都是圍繞着這個QXxx來進行操作的。代碼很直觀,selectFrom是select方法與from方法的合並,這里為了方便就不分開寫了,where中可以收可變參數Predicate,由於Predicate是一個接口,由user.username.eq或者user.uIndex.gt等等方法返回的都是BooleanExpression或者XXXExpression,這些XXXExpression都是Predicate的實現,故直接傳入,讓QueryDSL在內部做處理,其實Predicate也是實現了Expression接口,大家如果有興趣可以自行跟蹤源碼研究。

b、第二個方法也相當的直觀,跟sql的字面意思幾乎一模一樣。

c、第三個方法是第二個方法的排序寫法,主要用到了offerset、limit方法,根據傳入的pageable參數進行分頁,最后返回的結果是一個QuerResults類型的返回值,該返回值對象簡單的封裝了一些分頁的參數與返回的實體集,然調用者自己根據需求去取出使用。

d、第四個方法展示了日期查詢,也相當的直觀,大家嘗試了就知道了,主要使用到了between方法。

e、第五個方法是比較重要的方法,這個方法展示了如何進行部分字段的映射查詢,這個方法的目的是只查詢uerrname、userId、nickname、birthday四個字段,然后封裝到UserDTO中,最后返回。其中,由於select與from拆分了以后返回的泛型類型就是Tuple類型(Tuple是一個接口,它可以根據tuple.get(QUser.username)的方式獲取User.username的真實值,暫時將他理解為一個類型安全的Map就行),根據pageable參數做了分頁處理,fetch之后就返回了一個List<Tuple>對象。從fetch()方法之后,使用到了Stream,緊接着使用Java8的高階函數map,這個map函數的作用是將List<Tuple>中的Tuple元素依次轉換成List<UserDTO>中的UserDTO元素,在這個過程中我們還可以做bean的屬性類型轉換,將User的Date、Integer類型都轉換成String類型。最后,通過collect結束stream,返回一個我們需要的List<UserDTO>。

f、第六個方法與第五個方法的效果相同,使用QueryDSL的Projections實現。但是有一點,當User實體的屬性類型與UserDTO中的屬性類型不相同時,不方便轉換。除了屬性類型相同時轉換方便以外,還是建議使用map函數進行操作。

g、第七、第八個方法展示了QueryDSL與SpringDataJPA的聯合使用,由於我們的UserRepository繼承了QueryDslPredicateExecutor,所以獲得了聯合使用的支持。來看一看QueryDslPredicateExcutor接口的源碼:


   
   
  
  
          
  1. public interface QueryDslPredicateExecutor<T> {
  2. T findOne(Predicate var1);
  3. Iterable<T> findAll(Predicate var1);
  4. Iterable<T> findAll(Predicate var1, Sort var2);
  5. Iterable<T> findAll(Predicate var1, OrderSpecifier... var2);
  6. Iterable<T> findAll(OrderSpecifier... var1);
  7. Page<T> findAll(Predicate var1, Pageable var2);
  8. long count(Predicate var1);
  9. boolean exists(Predicate var1);
  10. }

這里面的方法大多數都是可以傳入Predicate類型的參數,說明還是圍繞着QUser來進行操作的,如傳入quser.username.eq("123")的方式,操作都非常簡單。以下是部分源碼,請看:


   
   
  
  
          
  1. /*
  2. * Copyright 2008-2017 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.data.jpa.repository.support;
  17. import java.io.Serializable;
  18. import java.util.List;
  19. import java.util.Map.Entry;
  20. import javax.persistence.EntityManager;
  21. import javax.persistence.LockModeType;
  22. import org.springframework.data.domain.Page;
  23. import org.springframework.data.domain.Pageable;
  24. import org.springframework.data.domain.Sort;
  25. import org.springframework.data.querydsl.EntityPathResolver;
  26. import org.springframework.data.querydsl.QSort;
  27. import org.springframework.data.querydsl.QueryDslPredicateExecutor;
  28. import org.springframework.data.querydsl.SimpleEntityPathResolver;
  29. import org.springframework.data.repository.support.PageableExecutionUtils;
  30. import org.springframework.data.repository.support.PageableExecutionUtils.TotalSupplier;
  31. import com.querydsl.core.types.EntityPath;
  32. import com.querydsl.core.types.OrderSpecifier;
  33. import com.querydsl.core.types.Predicate;
  34. import com.querydsl.core.types.dsl.PathBuilder;
  35. import com.querydsl.jpa.JPQLQuery;
  36. import com.querydsl.jpa.impl.AbstractJPAQuery;
  37. /**
  38. * QueryDsl specific extension of {@link SimpleJpaRepository} which adds implementation for
  39. * {@link QueryDslPredicateExecutor}.
  40. *
  41. * @author Oliver Gierke
  42. * @author Thomas Darimont
  43. * @author Mark Paluch
  44. * @author Jocelyn Ntakpe
  45. * @author Christoph Strobl
  46. */
  47. public class QueryDslJpaRepository<T, ID extends Serializable> extends SimpleJpaRepository<T, ID>
  48. implements QueryDslPredicateExecutor< T> {
  49. private static final EntityPathResolver DEFAULT_ENTITY_PATH_RESOLVER = SimpleEntityPathResolver.INSTANCE;
  50. private final EntityPath<T> path;
  51. private final PathBuilder<T> builder;
  52. private final Querydsl querydsl;
  53. /**
  54. * Creates a new {@link QueryDslJpaRepository} from the given domain class and {@link EntityManager}. This will use
  55. * the {@link SimpleEntityPathResolver} to translate the given domain class into an {@link EntityPath}.
  56. *
  57. * @param entityInformation must not be {@literal null}.
  58. * @param entityManager must not be {@literal null}.
  59. */
  60. public QueryDslJpaRepository(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager) {
  61. this(entityInformation, entityManager, DEFAULT_ENTITY_PATH_RESOLVER);
  62. }
  63. ...............
  64. ............

至於源碼,感興趣的同學可以自行跟蹤研究。

h、最后,我們的殺手鐧來了,JPA對動態條件拼接查詢支持一向都不太靈活,如果在mybatis中,我們使用if標簽可以很容易的實現動態查詢,但是在JPA中,就沒有那么方便了。SpringDataJPA給我們提供了Specification+JpaSpecificationExecutor幫我們解決,但是,在需要編寫某些復雜的動態條件拼接、分組之后又動態拼接的復雜查詢,可能就顯得力不從心了,這個時候可能需要直接對entityManager操作,然后對sql進行拼接,請看以下老代碼是怎么寫的


   
   
  
  
          
  1. //自定義動態報表原生sql查詢
  2. //只要isSelect不為空,那么就執行條件查詢:前端自行根據返回值判斷是否已經選題(大於0就是選了題的)
  3. public Page<StudentToAdminVO> findAllStudentToAdminVOPage(Pageable pageable, String majorId, Boolean isSelect, Boolean isSelectSuccess) {
  4. //設置條件
  5. StringBuffer where = new StringBuffer( " where 1=1 ");
  6. StringBuffer having = new StringBuffer( " having 1=1");
  7. if(!StringUtils.isEmpty(majorId)){
  8. where.append( " and s.major_id=:majorId ");
  9. }
  10. if(isSelect!= null){
  11. //是否選題了,只需要看查出的這個數是否大於零即可
  12. if(isSelect)
  13. having.append( " and count(se.id)>0 ");
  14. else
  15. having.append( " and count(se.id)=0 ");
  16. }
  17. if(isSelectSuccess != null){
  18. if(isSelectSuccess)
  19. having.append( " and max(se.is_select)>0");
  20. else
  21. having.append( " and (max(se.is_select) is null or max(se.is_select)<=0)");
  22. }
  23. //主體sql
  24. String sql = "select s.id, s.username, s.nickname, s.sclass, m.name majorName, count(se.id) as choose, max(se.is_select) as selectSuccess from student s"
  25. + " left join selection se on s.id=se.student_id "
  26. + " left join major m on m.id=s.major_id "
  27. + where
  28. + " group by s.id"
  29. + having;
  30. String countSql = null;
  31. //計算總記錄數sql
  32. if(isSelect!= null){
  33. countSql = "select count(*) from student s "
  34. + where
  35. + " and s.id in(select ss.id FROM student ss left join selection se on se.student_id=ss.id GROUP BY ss.id "
  36. + having
  37. + " )";
  38. } else{
  39. countSql = "select count(*) from student s " + where;
  40. }
  41. //創建原生查詢
  42. Query query = em.createNativeQuery(sql);
  43. Query countQuery = em.createNativeQuery(countSql);
  44. if(!StringUtils.isEmpty(majorId)){
  45. query.setParameter( "majorId", majorId);
  46. countQuery.setParameter( "majorId", majorId);
  47. }
  48. int total = Integer.valueOf(countQuery.getSingleResult().toString());
  49. // pageable.getPageNumber()==0 ? pageable.getOffset() : pageable.getOffset()-5
  50. if(pageable!= null){
  51. query.setFirstResult(pageable.getOffset());
  52. query.setMaxResults(pageable.getPageSize());
  53. }
  54. //對象映射
  55. query.unwrap(SQLQuery.class)
  56. .addScalar( "id", StandardBasicTypes.STRING)
  57. .addScalar( "username", StandardBasicTypes.STRING)
  58. .addScalar( "nickname", StandardBasicTypes.STRING)
  59. .addScalar( "sclass", StandardBasicTypes.STRING)
  60. .addScalar( "majorName", StandardBasicTypes.STRING)
  61. .addScalar( "choose", StandardBasicTypes.INTEGER)
  62. .addScalar( "selectSuccess", StandardBasicTypes.INTEGER)
  63. .setResultTransformer(Transformers.aliasToBean(StudentToAdminVO.class));
  64. return new PageImpl<StudentToAdminVO>(query.getResultList(), pageable, total);
  65. }

我們再來看一個對JPQL拼接的例子:


   
   
  
  
          
  1. /**
  2. * 動態查詢
  3. * @param pageable
  4. * @param isSelect 是否確選(只要非空,都相當於加了條件)
  5. * @param titleLike 根據title模糊查詢
  6. * @param teacherId 根據老師的id查詢
  7. * @return
  8. */
  9. Page<SubjectToTeacherVO> findAllSubjectToTeacherVO(Pageable pageable, Boolean isSelect, String titleLike,
  10. String teacherId, String majorId, String studentId){
  11. //條件組合
  12. StringBuffer where = new StringBuffer( " where 1=1 ");
  13. StringBuffer having = new StringBuffer();
  14. if(isSelect != null){
  15. if(isSelect)
  16. having.append( " having max(se.isSelection)>0 ");
  17. else
  18. having.append( " having ((max(se.isSelection) is null) or max(se.isSelection)<=0) ");
  19. }
  20. if(!StringUtils.isEmpty(titleLike))
  21. where.append( " and su.title like :titleLike");
  22. if(!StringUtils.isEmpty(teacherId))
  23. where.append( " and su.teacher.id=:teacherId");
  24. if(!StringUtils.isEmpty(majorId))
  25. where.append( " and su.major.id=:majorId");
  26. if(!StringUtils.isEmpty(studentId)){
  27. where.append( " and su.major.id=(select stu.major.id from Student stu where stu.id=:studentId)");
  28. }
  29. //主jpql 由於不能使用 if(exp1,rsul1,rsul2)只能用case when exp1 then rsul1 else rsul2 end
  30. String jpql = "select new cn.edu.glut.vo.SubjectToTeacherVO(su.id, su.title, cast(count(se.id) as int) as guysNum, max(se.isSelection) as choose, "
  31. + " (select ss.nickname from Selection as sel left join sel.student as ss where sel.subject.id=su.id and sel.isSelection=1) as stuName, "
  32. + " (select t.nickname from Teacher t where t.id=su.teacher.id) as teacherName, "
  33. + " ma.id as majorId, ma.name as majorName) "
  34. + " from Subject as su left join su.selections as se"
  35. + " left join su.major as ma "
  36. + where
  37. + " group by su.id "
  38. + having;
  39. String countJpql = null;
  40. if(isSelect != null)
  41. countJpql = "select count(*) from Subject su left join su.selections as se left join se.student as s"
  42. + where
  43. + " and su.id in(select s.id from Subject s left join s.selections se group by s.id "
  44. + having
  45. + " )";
  46. else
  47. countJpql = "select count(*) from Subject su left join su.selections as se left join se.student as s" + where;
  48. Query query = em.createQuery(jpql, SubjectToTeacherVO.class);
  49. Query countQuery = em.createQuery(countJpql);
  50. // pageable.getPageNumber()==0 ? pageable.getOffset() : pageable.getOffset()-5
  51. if( null != pageable){
  52. query.setFirstResult(pageable.getOffset());
  53. query.setMaxResults(pageable.getPageSize());
  54. }
  55. if(!StringUtils.isEmpty(titleLike)){
  56. query.setParameter( "titleLike", "%"+titleLike+ "%");
  57. countQuery.setParameter( "titleLike", "%"+titleLike+ "%");
  58. }
  59. if(!StringUtils.isEmpty(teacherId)){
  60. query.setParameter( "teacherId", teacherId);
  61. countQuery.setParameter( "teacherId", teacherId);
  62. }
  63. if(!StringUtils.isEmpty(majorId)){
  64. query.setParameter( "majorId", majorId);
  65. countQuery.setParameter( "majorId", majorId);
  66. }
  67. if(!StringUtils.isEmpty(studentId)){
  68. query.setParameter( "studentId", studentId);
  69. countQuery.setParameter( "studentId", studentId);
  70. }
  71. List<SubjectToTeacherVO> voList = query.getResultList();
  72. return new PageImpl<SubjectToTeacherVO>(voList, pageable, Integer.valueOf(countQuery.getSingleResult().toString()));
  73. }

說惡心一點都不過分...不知道小伙伴們覺得如何,反正我是忍不了了...

我們UserService中的最后兩個方法就是展示如何做動態查詢的,第一個方法結合了與SpringDataJPA整合QueryDSL的findAll來實現,第二個方法使用QueryDSL本身的API進行實現,其中Page是Spring自身的的。第一行user.isNotNull.or(user.isNull())可以做到類似where 1=1的效果以便於后面進行的拼接,當然,主鍵是不能為空的,所以此處也可以只寫user.isNotNull()也可以。緊接着是一串的三目運算符表達式,以第一行三目表達式為例,表達意義在於:如果用戶名為空,就返回定義好的predicate;如果不為空,就使用ExpressionUtils的and方法將username作為條件進行組合,ExpressionUtils的and方法返回值也是一個Predicate。下面的幾條三目運算符與第一條是類似的。最后使用findAll方法傳入分頁參數與條件參數predicate,相比起上面頭疼的自己拼接,是不是簡潔了很多?

最后一個方法展示的是如果有分組條件時進行的查詢,相信大家就字面意思理解也能知道大概的意思了,前半部分代碼是相同的,groupby之后需要插入條件是要用到having的。就與sql的規范一樣,如果對分組與having還不了解,希望大家多多google哦。

2.2.2 多表使用

對於多表使用,大致與單表類似。我們先創建一個一對多的關系,一個部門對應有多個用戶,創建Department實體:


   
   
  
  
          
  1. @Data
  2. @Entity
  3. @Table(name = "t_department")
  4. public class Department {
  5. @Id
  6. @GeneratedValue(strategy = GenerationType.IDENTITY)
  7. private Integer deptId; //部門id
  8. private String deptName; //部門名稱
  9. private Date createDate; //創建時間
  10. }

在User實體需要稍稍修改,User實體中添加department建模:


   
   
  
  
          
  1. @Data
  2. @Entity
  3. @Table(name = "t_user")
  4. public class User {
  5. @Id
  6. @GeneratedValue(strategy = GenerationType.IDENTITY)
  7. private Integer userId;
  8. private String username;
  9. private String password;
  10. private String nickName;
  11. private Date birthday;
  12. private BigDecimal uIndex; //排序號
  13. //一對多映射
  14. @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
  15. @JoinColumn(name = "department_id")
  16. private Department department; //部門實體
  17. }

我們假設有一個這樣的需求,前端需要展示根據部門deptId來查詢用戶的基礎信息,在展示用戶基礎信息的同時需要展示該用戶所屬的部門名稱以及該部門創建的時間。那么,我們創建一個這樣的DTO來滿足前端的需求:


   
   
  
  
          
  1. @Data
  2. @Builder
  3. public class UserDeptDTO {
  4. //用戶基礎信息
  5. private String username; //用戶名
  6. private String nickname; //昵稱
  7. private String birthday; //用戶生日
  8. //用戶的部門信息
  9. private String deptName; //用戶所屬部門
  10. private String deptBirth; //部門創建的時間
  11. }

大家一定想到了使用部分字段映射的投影查詢,接下來我們在UserService中添加如下代碼:


   
   
  
  
          
  1. /**
  2. * 根據部門的id查詢用戶的基本信息+用戶所屬部門信息,並且使用UserDeptDTO進行封裝返回給前端展示
  3. * @param departmentId
  4. * @return
  5. */
  6. public List<UserDeptDTO> findByDepatmentIdDTO(int departmentId) {
  7. QUser user = QUser.user;
  8. QDepartment department = QDepartment.department;
  9. //直接返回
  10. return jpaQueryFactory
  11. //投影只去部分字段
  12. .select(
  13. user.username,
  14. user.nickName,
  15. user.birthday,
  16. department.deptName,
  17. department.createDate
  18. )
  19. .from(user)
  20. //聯合查詢
  21. .join(user.department, department)
  22. .where(department.deptId.eq(departmentId))
  23. .fetch()
  24. //lambda開始
  25. .stream()
  26. .map(tuple ->
  27. //需要做類型轉換,所以使用map函數非常適合
  28. UserDeptDTO.builder()
  29. .username(tuple.get(user.username))
  30. .nickname(tuple.get(user.nickName))
  31. .birthday( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(tuple.get(user.birthday)))
  32. .deptName(tuple.get(department.deptName))
  33. .deptBirth( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(tuple.get(department.createDate)))
  34. .build()
  35. )
  36. .collect(Collectors.toList());
  37. }

select部分是選擇需要查詢的字段,leftjoin的第一個參數是用戶所關聯的部門,第二個參數可以當做該user.department別名來使用,往后看即可理解。where中只有一個很簡單的條件,即根據部門的id來進行查詢,最后使用stream來將Tuple轉換成UserDeptDTO,中間在map函數中對一些屬性的類型進行了轉換。其他的關聯操作與上述代碼類似,對於orderBy、groupBy、聚合函數、分頁操作的API都與單表的類似,只是where中的條件自己進行適配即可。

在應用開發中我們可能不會在代碼中設置@ManyToOne、@ManyToMany這種類型的“強建模”,而是在隨從的Entity中僅僅聲明一個外鍵屬性,比如User實體的下面代碼,只是添加了一個departmentId:


   
   
  
  
          
  1. @Data
  2. @Entity
  3. @Table(name = "t_user")
  4. public class User {
  5. @Id
  6. @GeneratedValue(strategy = GenerationType.IDENTITY)
  7. private Integer userId;
  8. private String username;
  9. private String password;
  10. private String nickName;
  11. private Date birthday;
  12. private BigDecimal uIndex; //排序號
  13. private Integer departmentId;
  14. }

這時候我們的多表關聯業務代碼只需要稍作修改就可以:


   
   
  
  
          
  1. /**
  2. * 根據部門的id查詢用戶的基本信息+用戶所屬部門信息,並且使用UserDeptDTO進行封裝返回給前端展示
  3. *
  4. * @param departmentId
  5. * @return
  6. */
  7. public List<UserDeptDTO> findByDepatmentIdDTO(int departmentId) {
  8. QUser user = QUser.user;
  9. QDepartment department = QDepartment.department;
  10. //直接返回
  11. return jpaQueryFactory
  12. //投影只去部分字段
  13. .select(
  14. user.username,
  15. user.nickName,
  16. user.birthday,
  17. department.deptName,
  18. department.createDate
  19. )
  20. .from(user, department)
  21. //聯合查詢
  22. .where(
  23. user.departmentId.eq(department.deptId).and(department.deptId.eq(departmentId))
  24. )
  25. .fetch()
  26. //lambda開始
  27. .stream()
  28. .map(tuple ->
  29. //需要做類型轉換,所以使用map函數非常適合
  30. UserDeptDTO.builder()
  31. .username(tuple.get(user.username))
  32. .nickname(tuple.get(user.nickName))
  33. .birthday( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(tuple.get(user.birthday)))
  34. .deptName(tuple.get(department.deptName))
  35. .deptBirth( new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(tuple.get(department.createDate)))
  36. .build()
  37. )
  38. .collect(Collectors.toList());
  39. }

我們在from中多加了department參數,在where中多加了一個user.department.eq(department.deptId)條件,與sql中的操作類似。為什么在這里不適用join....on....呢,原因是我們使用的是QueryDSL-JPA,QueryDSL對JPA支持是全面的,當然也有QueryDSL-SQL,但是配置起來會比較麻煩。如果大家想了解QueryDSL-SQL可以點擊這里進行了解。

3 結語

  使用SpringDataJPA能夠解決我們大多數問題,但是在處理復雜條件、動態條件、投影查詢時可能QueryDSL JPA更加直觀,而且SpringDataJPA對QueryDSL有着非常好的支持,SpringDataJPA+QueryDSL在我眼里看來是天生一對,互相補漏。在使用一般查詢、能夠滿足基礎條件的查詢我們使用SpringDataJPA更加簡潔方便,當遇到復雜、投影、動態查詢時我們可以考慮使用QueryDSL做開發。以上方案可以解決大多數持久層開發問題,當然,如果問題特別刁鑽,還是不能滿足你的需求,你也可以考慮直接操作HQL或者SQL。

  今天的分享就到此結束了,小伙伴們如果有更好的建議,歡迎大家提出指正,但是請不要謾罵與辱罵,寫一篇博客實屬不易。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM