這篇文章給大家分享的是有關(guān)怎么實(shí)現(xiàn)JPA多條件復(fù)雜SQL動(dòng)態(tài)分頁(yè)查詢(xún)功能的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。
創(chuàng)新互聯(lián)公司 是一家專(zhuān)注于成都網(wǎng)站制作 、成都做網(wǎng)站與策劃設(shè)計(jì),石泉網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)公司 做網(wǎng)站,專(zhuān)注于網(wǎng)站建設(shè)10余年,網(wǎng)設(shè)計(jì)領(lǐng)域的專(zhuān)業(yè)建站公司;建站業(yè)務(wù)涵蓋:石泉等地區(qū)。石泉做網(wǎng)站價(jià)格咨詢(xún):13518219792
概述
ORM映射為我們帶來(lái)便利的同時(shí),也失去了較大靈活性,如果SQL較復(fù)雜,要進(jìn)行動(dòng)態(tài)查詢(xún),那必定是一件頭疼的事情(也可能是lz還沒(méi)發(fā)現(xiàn)好的方法),記錄下自己用的三種復(fù)雜查詢(xún)方式。
環(huán)境
springBoot
IDEA2017.3.4
JDK8
pom.xml
4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.6.RELEASE com.xmlxy seasgame 0.0.1-SNAPSHOT seasgame Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-data-jpa MySQL mysql-connector-java runtime org.springframework.boot spring-boot-devtools runtime true org.projectlombok lombok true org.springframework.boot spring-boot-starter-data-jpa io.springfox springfox-swagger2 2.8.0 io.springfox springfox-swagger-ui 2.8.0 org.springframework.boot spring-boot-configuration-processor true org.springframework.boot spring-boot-starter-security net.sf.json-lib json-lib 2.2.2 jdk15 com.belerweb pinyin4j 2.5.1 org.springframework.boot spring-boot-starter-thymeleaf javax.servlet javax.servlet-api 3.1.0 provided war org.springframework.boot spring-boot-maven-plugin org.apache.maven.plugins maven-compiler-plugin 1.8 1.8 seasgame org.apache.maven.plugins maven-compiler-plugin 2.3.2 ${project.build.sourceEncoding} 1.7 1.7 org.apache.maven.plugins maven-surefire-plugin true
@Query
當(dāng)一個(gè)SQL較為復(fù)雜時(shí),第一個(gè)想到的就是原生的SQL語(yǔ)句。如果只是簡(jiǎn)單的查詢(xún),那情況還沒(méi)這么糟糕
@Query(value = " SELECT IFNULL(sum(right_num),0) sumRight FROM t_record WHERE record_owner_id = ?1 AND responder_no = ?2 ",nativeQuery = true) Map sumRightNum(int studentId,int responderNo);
但如果需要進(jìn)行動(dòng)態(tài)查詢(xún),或更改,那這個(gè)value就變得復(fù)雜了。
package com.xmlxy.seasgame.dao;import com.xmlxy.seasgame.entity.ScoreEntity;import org.springframework.data.jpa.repository.Modifying;import org.springframework.data.jpa.repository.Query;import org.springframework.data.repository.CrudRepository;import org.springframework.data.repository.query.Param;import org.springframework.transaction.annotation.Transactional;import java.util.List;/** * * Description: * @author hwc * @date 2019/9/5 * @return*/ public interface ScoreDao extends CrudRepository{ /** * * Description: *@param scoreEntity * @author hwc * @date 2019/9/6 */ @Transactional(rollbackFor = Exception.class) @Modifying @Query(value = "UPDATE t_score t SET " + "t.responder_no = CASE WHEN :#{#scoreEntity.responderNo} IS NULL THEN t.responder_no ELSE :#{#scoreEntity.responderNo} END," + "t.max_level = CASE WHEN :#{#scoreEntity.maxLevel} IS NULL THEN t.max_level ELSE :#{#scoreEntity.maxLevel} END," + "t.right_num = CASE WHEN :#{#scoreEntity.rightNum} IS NULL THEN t.right_num ELSE :#{#scoreEntity.rightNum} END," + "t.use_time = CASE WHEN :#{#scoreEntity.userTime} IS NULL THEN t.use_time ELSE :#{#scoreEntity.userTime} END WHERE student_id = :#{#scoreEntity.getStudentId()}",nativeQuery = true) void updateScore(@Param("scoreEntity") ScoreEntity scoreEntity);}
JPQL
如果Java代碼內(nèi)發(fā)出JPQL查詢(xún),就需要利用到EntityManager的響應(yīng)方法了。一般執(zhí)行以下流程
獲取一個(gè)EntityManager實(shí)例
調(diào)用實(shí)例的方法createQuery,創(chuàng)建一個(gè)Query實(shí)例,如果有需要可以指定檢索的最大數(shù)量和起始位置
使用Query方法getResultList執(zhí)行查詢(xún),當(dāng)然更新和刪除操作得使用executeUpdate執(zhí)行
進(jìn)行一個(gè)復(fù)雜的動(dòng)態(tài)SQL查詢(xún)
public Page getScoreByRank(int gradeId,int classId,Pageable pageable) { StringBuilder countSelectSql = new StringBuilder(""); countSelectSql.append(" SELECT COUNT(*) "); countSelectSql.append(" FROM "); countSelectSql.append(" t_score s, "); countSelectSql.append(" t_student st "); countSelectSql.append(" WHERE "); countSelectSql.append(" s.student_id = st.student_id "); StringBuilder selectSql = new StringBuilder(); selectSql.append(" SELECT s.student_id,st.real_name,st.student_class,s.max_level,s.use_time,s.right_num "); selectSql.append(" FROM t_score s "); selectSql.append(" JOIN t_student st ON s.student_id = st.student_id "); selectSql.append(" WHERE 1 = 1 "); Map params = new HashMap<>(); StringBuilder whereSql = new StringBuilder(); if (gradeId != -1) { whereSql.append(" AND st.student_grade = :student_grade "); params.put("student_grade",gradeId); } /**班級(jí)ID*/ if (classId != -1) { whereSql.append(" AND st.student_class = :classId "); params.put("classId",classId); } String orderSql = " ORDER BY s.max_level DESC,s.use_time,s.right_num ASC "; String countSql = new StringBuilder().append(countSelectSql).append(whereSql).toString(); Query countQuery = entityManager.createNativeQuery(countSql); for (Map.Entry entry : params.entrySet()) { countQuery.setParameter(entry.getKey(),entry.getValue()); } BigInteger totalCount = (BigInteger)countQuery.getSingleResult(); String querySql = new StringBuilder().append(selectSql).append(whereSql).append(orderSql).toString(); Query query = entityManager.createNativeQuery(querySql,RankEntity.class); for (Map.Entry entry:params.entrySet()) { query.setParameter(entry.getKey(),entry.getValue()); } query.setFirstResult((int) pageable.getOffset()); query.setMaxResults(pageable.getPageSize()); List rankEntities = query.getResultList(); Page page = new PageImpl<>(rankEntities,pageable,totalCount.longValue()); return page; }
注意:如果沒(méi)有重新定義Pageable那么pageNumber必須減1,因?yàn)槭菑?開(kāi)始的。
Criteria
這是一種規(guī)范查詢(xún)是以元模型的概念為基礎(chǔ)的,這個(gè)元模型可以是實(shí)體累,嵌入類(lèi),或者映射的父類(lèi),簡(jiǎn)單介紹幾個(gè)里面用到接口。
CriteraQuery是一個(gè)特定的頂層查詢(xún)對(duì)象,里面包含select,from,where,order by等各個(gè)部分,然而他只對(duì)實(shí)體類(lèi)或嵌入類(lèi)的標(biāo)準(zhǔn)查詢(xún)起作用。
Root標(biāo)準(zhǔn)查詢(xún)的根對(duì)象,根定義了實(shí)體類(lèi)型,是你想要查詢(xún)要獲得的結(jié)果,也可以添加查詢(xún)條件,結(jié)合實(shí)體管理對(duì)象得到查詢(xún)的對(duì)象。
CriteriaBuilder接口用來(lái)構(gòu)建CritiaQuery的構(gòu)建器
StudentEntity類(lèi)
package com.xmlxy.seasgame.entity;import io.swagger.annotations.ApiModel;import lombok.Data;import javax.persistence.*;import javax.print.attribute.standard.MediaSize;import java.io.Serializable;/** * * Description:學(xué)生對(duì)象 * @param * @author hwc * @date 2019/8/8 */@Entity@Table(name = "t_base_student")@ApiModel@Datapublic class StudentEntity implements Serializable{ private static final long serialVersionUID = 546L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "student_id") private Integer studentId; @Column(name = "student_grade") private Integer studentGrade; @Column(name = "student_class") private Integer studentClass; @Column(name = "address") private String address; @Column(name = "telephone") private Integer telephone; @Column(name = "real_name") private String realName; @Column(name = "id_number") private String idNumber; @Column(name = "study_id") private String studyId; @Column(name = "is_delete") private int isDelete; @Column(name = "uuid") private String uuid;}
dao層
public interface StudentDao extends JpaRepository,JpaSpecificationExecutor{}
動(dòng)態(tài)查詢(xún)
public Page getTeacherClassStudent(int pageNumber,int pageSize,int gradeId, int classId,String keyword) { pageNumber = pageNumber < 0 ? 0 : pageNumber; pageSize = pageSize < 0 ? 10 : pageSize; Specification specification = new Specification() { @Override public Predicate toPredicate(Root root, CriteriaQuery> criteriaQuery, CriteriaBuilder criteriaBuilder) { //page : 0 開(kāi)始, limit : 默認(rèn)為 10 List predicates = new ArrayList<>(); predicates.add(criteriaBuilder.equal(root.get("studentGrade"),gradeId)); predicates.add(criteriaBuilder.equal(root.get("studentClass"),classId)); if (!Constant.isEmptyString(keyword)) { predicates.add(criteriaBuilder.like(root.get("realName").as(String.class),"%" + keyword + "%")); } return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); } }; /*studentId必須是實(shí)體類(lèi)屬性與數(shù)據(jù)庫(kù)對(duì)應(yīng),否則報(bào)ropertyReferenceException異常*/ PageRequest page = new PageRequest(pageNumber,pageSize,Sort.Direction.ASC,"studentId"); Page pages = studentDao.findAll(specification,page); return pages; }
因?yàn)檫@個(gè)項(xiàng)目應(yīng)用比較簡(jiǎn)單,所以條件只有一個(gè),如果條件較多,甚至可以定義一個(gè)專(zhuān)門(mén)的類(lèi)去接收拼接參數(shù),然后判
斷,成立就add進(jìn)去。
感謝各位的閱讀!關(guān)于“怎么實(shí)現(xiàn)JPA多條件復(fù)雜SQL動(dòng)態(tài)分頁(yè)查詢(xún)功能”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
網(wǎng)頁(yè)標(biāo)題:怎么實(shí)現(xiàn)JPA多條件復(fù)雜SQL動(dòng)態(tài)分頁(yè)查詢(xún)功能
本文路徑:
http://weahome.cn/article/ipsgdi.html