您好,登錄后才能下訂單哦!
怎么在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.測試結果:
這是查詢日志:
看完上述內容,你們掌握怎么在Spring Data JPA中引入Querydsl的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。