在Spring Data JPA中引入Querydsl的實現方式
一、環境說明
基礎框架采用Spring Boot、Spring Data JPA、Hibernate。在動態查詢中,有一種方式是采用Querydsl的方式。
二、具體配置
1、在pom.xml中,引入相關包和配置插件。
(1)引入包(註:不需要版本號,Spring Boot 會自動匹配合適的版本)
<!-- Querydsl相關包 --> <dependency> <groupId>com.querydsl</groupId> <artifactId>querydsl-jpa</artifactId> </dependency> <dependency> <groupId>com.querydsl</groupId> <artifactId>querydsl-apt</artifactId> </dependency>
(2)配置插件:主要用來生成“查詢對象”。
<plugin> <groupId>com.mysema.maven</groupId> <artifactId>maven-apt-plugin</artifactId> <version>1.0.4</version> <executions> <execution> <phase>generate-sources</phase> <goals> <goal>process</goal> </goals> <configuration> <outputDirectory>target/generated-sources</outputDirectory> <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor> </configuration> </execution> </executions> </plugin>
2、設置源文件夾
經過上面pom.xml的配置後,就在 target/generated-sources 文件夾下面自動生成“查詢對象”。需要將該文件夾設置成“源文件夾”,以便可以將下面的java文件進行編譯使用。
生成的查詢對象,都是在原實體(bo)類的名字前,加上 Q 表示。
3、dao中繼承接口QueryDslPredicateExecutor
4、在service層使用 Querydsl方式進行是查詢,例如:
三、寫在最後
此文僅作為引入Querydsl的筆記,並不代表作者本人推薦使用Querydsl。就實際應用而言,個人更傾向於使用 JPA Criteria 的方式來實現動態查詢,其接口是JpaSpecificationExecutor。
補充:Spring-data-jpa擴展查詢 QueryDSL 實踐
說明: QueryDSL是以函數連接的方式將SQL調用進行拆分,比較spring data jpa中的criteria查詢方法還是簡潔瞭不少。
用例:通過服務調用,使用querydsl進行查詢並直接返回DTO對象(自定義傳輸對象(根據業務需求),註意區別於Entity)
實踐步驟:
1.創建user與depart表,使用外鍵進行關聯,並插入一些模擬數據。
2.創建sprintboot項目,在pom文件中加入以下依賴:
<dependency> <groupId>com.querydsl</groupId> <artifactId>querydsl-jpa</artifactId> </dependency> <dependency> <groupId>com.querydsl</groupId> <artifactId>querydsl-apt</artifactId> <scope>provided</scope> </dependency>
3.在pom文件中<build>–><plugins>節點下加入plugin:
<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> <dependencies> <dependency> <groupId>com.querydsl</groupId> <artifactId>querydsl-apt</artifactId> <version>4.1.3</version> </dependency> </dependencies> </plugin>
4.生成相關entity與repository對象,這裡以user為例:
註意:repository需要繼承 QueryDslPredicateExecutor<T>接口。
5.生成業務傳輸對象DTO:
package com.test.demo.db; // import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * User generated by hbm2java */ @Entity @Table(name = "user", catalog = "testdb") public class User implements java.io.Serializable { private Integer id; private Department department; private String username; public User() { } public User(Department department, String username) { this.department = department; this.username = username; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "fk_depart") public Department getDepartment() { return this.department; } public void setDepartment(Department department) { this.department = department; } @Column(name = "username", length = 45) public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } }
package com.test.demo.repo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.querydsl.QueryDslPredicateExecutor; import org.springframework.stereotype.Repository; import com.test.demo.db.User; @Repository public interface UserRepository extends QueryDslPredicateExecutor<User>, JpaRepository<User, Integer>,JpaSpecificationExecutor<User>{ }
註意:repository需要繼承 QueryDslPredicateExecutor<T>接口。
5.生成業務傳輸對象DTO:
package com.test.demo.controller; import com.querydsl.core.annotations.QueryProjection; import lombok.Data; @SuppressWarnings("unused") public @Data class UserDTO { private String username; private String departname; }
6.創建controller進行測試:
package com.test.demo.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.querydsl.core.types.Projections; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.jpa.impl.JPAQuery; import com.querydsl.jpa.impl.JPAQueryFactory; import com.test.demo.db.QUser; import com.test.demo.repo.UserRepository; @RestController @RequestMapping("/") public class TestController { @Autowired UserRepository userRepo; @Autowired @PersistenceContext EntityManager em; private JPAQueryFactory queryFactory; @PostConstruct public void init() { queryFactory = new JPAQueryFactory(em); } @RequestMapping("/users") Object getUsers(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page, @RequestParam(value = "size", required = false, defaultValue = "10") Integer size, @RequestParam(value = "name", required = false) String name, @RequestParam(value = "depart", required = false) String depart) { QUser user = QUser.user; JPAQuery<UserDTO> query = queryFactory .select(Projections.bean(UserDTO.class, user.username, user.department.name.as("departname"))) .from(user); BooleanExpression pre = null; if (name!=null && !name.isEmpty()) { pre = user.username.startsWith(name); } if (depart!=null && !depart.isEmpty()) { pre = user.department.name.startsWith(depart); } query.where(pre); query.limit(size); query.offset((page-1)*size); List<UserDTO> result = query.fetch(); Map<String, Object> map = new HashMap<>(); map.put("total", userRepo.count(pre)); map.put("data", result); return map; } }
註:這裡就是使用querydsl進行查詢,並直接轉換需要的屬性至DTO。並且代碼中的pre是可以根據參數動態拼接的。
7.測試結果:
這是查詢日志:
完。
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。
推薦閱讀:
- SpringBoot如何獲取application.properties中自定義的值
- Spring boot基於JPA訪問MySQL數據庫的實現
- 詳解IDEA中便捷內存數據庫H2的最簡使用方式
- Springboot如何根據實體類生成數據庫表
- 搭建MyBatis-Plus框架並進行數據庫增刪改查功能