日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

springboot-jpa-querydsl

發布時間:2023/12/20 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springboot-jpa-querydsl 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

springboot-jpa-querydsl

  • 新建項目
    • build.gradle
    • application.properties
    • 文件目錄結構:
    • 啟動類
    • 配置類
    • 控制器類Controller
    • 實體類UserEntity
    • 業務層
    • 持久層
    • 入參類
  • QueryDsl代碼生成

jpa對于簡單的增刪改查非常方便,但是復雜查詢,如多參數動態查詢,各種條件查詢,非常費勁。
QueryDsl是對jpa查詢的增強,語法就像寫sql,可以自由組合條件,也可以聯表查詢、分頁查詢等,非常方便;

新建項目

build.gradle

plugins {id 'org.springframework.boot' version '2.6.2'id 'io.spring.dependency-management' version '1.0.11.RELEASE'id 'java' }group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '1.8'configurations {compileOnly {extendsFrom annotationProcessor} }repositories {maven {url 'https://maven.aliyun.com/repository/public/'} }dependencies {implementation 'org.springframework.boot:spring-boot-starter-data-jpa'implementation 'org.springframework.boot:spring-boot-starter-web'implementation 'org.apache.commons:commons-lang3:3.9'compileOnly 'org.projectlombok:lombok'runtimeOnly 'mysql:mysql-connector-java'annotationProcessor 'org.projectlombok:lombok'testImplementation 'org.springframework.boot:spring-boot-starter-test'// querydslimplementation ('com.querydsl:querydsl-jpa')implementation ('com.querydsl:querydsl-apt')//關鍵地方(記得開啟annotationProcessor)annotationProcessor("com.querydsl:querydsl-apt:5.0.0:jpa","org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.2.Final","javax.annotation:javax.annotation-api:1.3.2","org.projectlombok:lombok") }test {useJUnitPlatform() }

application.properties

server.port=8080spring.jpa.show-sql=false spring.jpa.hibernate.ddl-auto=none spring.jpa.generate-ddl=false spring.jpa.properties.hibernate.show_sql=false spring.jpa.properties.hibernate.jdbc.time_zone=Asia/Shanghai spring.datasource.name=demo spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false&useUnicode=true&zeroDateTimeBehavior=convertToNull spring.datasource.username=root spring.datasource.password=root spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8

文件目錄結構:

. ├── main │ ├── java │ │ └── com │ │ └── example │ │ └── demo │ │ ├── Application.java │ │ ├── config │ │ │ ├── QueryDslOrderUtil.java │ │ │ └── QuerydslConfig.java │ │ ├── controller │ │ │ └── UserController.java │ │ ├── entity │ │ │ └── UserEntity.java │ │ ├── params │ │ │ └── UserQueryForm.java │ │ ├── reporsitory │ │ │ └── UserRepository.java │ │ └── service │ │ ├── UserService.java │ │ └── impl │ │ └── UserServiceImpl.java │ └── resources │ ├── application.properties │ ├── static │ └── templates └── test└── java└── com└── example└── demo└── ApplicationTests.java

啟動類

package com.example.demo;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling;@EntityScan(basePackages = "com.example.demo.entity") @EnableJpaRepositories(basePackages = "com.example.demo") @EnableJpaAuditing @EnableScheduling @EnableAsync @SpringBootApplication public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}

配置類

  • querydsl工廠配置類QuerydslConfig
  • package com.example.demo.config;import com.querydsl.jpa.impl.JPAQueryFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext;/*** QueryDSL配置類*/ @Configuration public class QuerydslConfig {@Resource@PersistenceContextprivate EntityManager entityManager;@Beanpublic JPAQueryFactory queryFactory() {return new JPAQueryFactory(entityManager);}}
  • 分頁配置類QueryDslOrderUtil
  • package com.example.demo.config;import com.querydsl.core.types.Order; import com.querydsl.core.types.OrderSpecifier; import com.querydsl.core.types.dsl.EntityPathBase;/*** 排序工具類** @author CCL* @createTime 2021年12月06日 13:09:00*/ public class QueryDslOrderUtil {/*** 根據入參動態排序* 使用示例: jpaQuery.orderBy(QueryDslOrderUtil.getSortedColumn(qSysUserEntity,params.getSortType(),params.getSortField* ()));** @param pathBase q實體* @param sortType 排序類型,升序ASC,降序DESC* @param sortField 排序字段名* @param <T>* @return*/public static <T> OrderSpecifier<?> orderByField(EntityPathBase<T> pathBase, String sortType, String sortField) {/*if (StringUtils.isAnyBlank(sortType, sortField)) {sortType = "desc";sortField = "createTime";}*/Order order = "ascend".equalsIgnoreCase(sortType) ? Order.ASC : Order.DESC;com.querydsl.core.types.Path<Object> fieldPath = com.querydsl.core.types.dsl.Expressions.path(Object.class,pathBase, sortField);return new OrderSpecifier(order, fieldPath);} }

    控制器類Controller

    package com.example.demo.controller;import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;@RestController public class UserController {@Autowiredprivate UserService userService;@GetMapping("/getAllUsers")public Object getAllUsers() {return userService.getAllUsers();} }

    實體類UserEntity

    package com.example.demo.entity;import lombok.Data; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.annotations.SelectBeforeUpdate; import org.springframework.data.jpa.domain.support.AuditingEntityListener;import javax.persistence.*; import java.util.Date; import java.util.List;@Data @Entity @Table(name = "t_user") @SelectBeforeUpdate @DynamicInsert @DynamicUpdate @EntityListeners(value = AuditingEntityListener.class) public class UserEntity {/*** 用戶ID*/@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long userId;/*** 用戶名*/private String username;/*** 密碼*/// @NotBlank(message="密碼不能為空", groups = AddGroup.class)private String password;/*** 鹽*/private String salt;/*** 郵箱*/private String email;/*** 手機號*/private String mobile;/*** 狀態 0刪除,1正常,2待激活,3禁用*/private Integer status;/*** 角色ID列表*/@Transientprivate List<Long> roleIdList;/*** 創建者ID*/private Long createUserId;/*** 創建時間*/private Date createTime;/*** 部門ID*/private Long deptId;/*** 是否默認密碼*/private Boolean isInitPwd;/*** 是否超級管理員*/@Transientprivate boolean superManager; }

    業務層

  • 接口
  • package com.example.demo.service;import com.example.demo.entity.UserEntity;import java.util.List;public interface UserService {List<UserEntity> getAllUsers(); }
  • 實現類
  • package com.example.demo.service.impl;import com.example.demo.config.QueryDslOrderUtil; import com.example.demo.entity.QUserEntity; import com.example.demo.entity.UserEntity; import com.example.demo.params.UserQueryForm; import com.example.demo.reporsitory.UserRepository; import com.example.demo.service.UserService; import com.querydsl.core.Tuple; import com.querydsl.jpa.impl.JPAQuery; import com.querydsl.jpa.impl.JPAQueryFactory; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils;import java.util.Collections; import java.util.List;@Service @Slf4j public class UserServiceImpl implements UserService {@Autowiredprivate JPAQueryFactory jpaQueryFactory;@Autowiredprivate UserRepository userRepository;private final QUserEntity qUserEntity = QUserEntity.userEntity;/*** 查詢所有-querydsl** @return*/@Overridepublic List<UserEntity> getAllUsers() {return jpaQueryFactory.select(qUserEntity).from(qUserEntity).fetch();}public List<UserEntity> getByParam(UserEntity userEntity) {JPAQuery<UserEntity> query = jpaQueryFactory.select(qUserEntity).from(qUserEntity);return jpaQueryFactory.select(qUserEntity).from(qUserEntity).fetch();}/*** querydsl 分頁復雜查詢** @param params* @return*/public List<UserEntity> queryPage(UserQueryForm params) {JPAQuery<UserEntity> query = jpaQueryFactory.select(qUserEntity).from(qUserEntity);if (StringUtils.isNotBlank(params.getUsername())) {query.where(qUserEntity.username.like("%" + params.getUsername() + "%"));}if (StringUtils.isNotBlank(params.getMobile())) {query.where(qUserEntity.mobile.eq(params.getMobile()));}if (StringUtils.isNotBlank(params.getEmail())) {query.where(qUserEntity.email.eq(params.getEmail()));}if (!CollectionUtils.isEmpty(params.getDeptIdList())) {query.where(qUserEntity.deptId.in(params.getDeptIdList()));}//根據入參排序if (StringUtils.isNotBlank(params.getSortField())) {query.orderBy(QueryDslOrderUtil.orderByField(qUserEntity, params.getSortType(), params.getSortField()));} else {//默認排序query.orderBy(qUserEntity.createTime.desc());}query.where(qUserEntity.status.ne(1));List<UserEntity> userList = query.offset((params.getPageNum() - 1) * params.getPageSize()).limit(params.getPageSize()).fetch();return userList;}/*** 示例: 此方法中有些類沒有貼出來,看使用語法即可* @param params* @return*/public PageInfo queryPage2(UserQueryForm params) {JPAQuery<Tuple> query = jpaQueryFactory.select(qUserEntity,qSysDeptEntity.deptName).from(qUserEntity).leftJoin(qSysUserRoleEntity).on(qUserEntity.userId.eq(qSysUserRoleEntity.userId)).leftJoin(qSysDeptEntity).on(qSysDeptEntity.id.eq(qUserEntity.deptId));if (StringUtils.isNotBlank(params.getUsername())) {query.where(qUserEntity.username.like("%" + params.getUsername() + "%"));}if (StringUtils.isNotBlank(params.getMobile())) {query.where(qUserEntity.mobile.like("%" + params.getMobile() + "%"));}if (StringUtils.isNotBlank(params.getEmail())) {query.where(qUserEntity.email.like("%" + params.getEmail() + "%"));}if (!CollectionUtils.isEmpty(params.getDeptIdList())) {query.where(qUserEntity.deptId.in(params.getDeptIdList()));}if (params.getRoleId() != null) {query.where(qSysUserRoleEntity.roleId.eq(params.getRoleId()));}//根據入參排序if (StringUtils.isNotBlank(params.getSortField())) {String sortField = params.getSortField();if (StringUtils.equals("deptName", sortField)) {query.orderBy(QueryDslOrderUtil.orderByField(qSysDeptEntity, params.getSortType(), params.getSortField()));} else {query.orderBy(QueryDslOrderUtil.orderByField(qUserEntity, params.getSortType(), params.getSortField()));}} else {//默認排序query.orderBy(qUserEntity.createTime.desc());}query.where(qUserEntity.status.ne(0));List<Tuple> fetch = Collections.emptyList();try {fetch = query.offset((params.getPageNum() - 1) * params.getPageSize()).limit(params.getPageSize()).fetch();} catch (Exception e) {log.error("用戶分頁查詢異常", e);}return new PageInfo(userList, (int) query.stream().count(), params.getPageSize(), params.getPageNum());}/*** 查詢所有-repository** @return*/public List<UserEntity> getAllUsers2() {return userRepository.findAll();}}

    持久層

    package com.example.demo.reporsitory;import com.example.demo.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.stereotype.Repository;/*** 這里面提供了很多通用方法,如findAll.findById,save,delete,update等等* 適用于簡單的增刪改查,非常方便*/ @Repository public interface UserRepository extends JpaRepository<UserEntity, Long>, QuerydslPredicateExecutor<UserEntity> {}

    入參類

    package com.example.demo.params;import lombok.Data;import java.util.List;@Data public class UserQueryForm {private String username;private String mobile;private Long roleId;private String email;private List<Long> deptIdList;private int pageNum = 1;private int pageSize = 10;String sortType = "ascend";String sortField; }

    QueryDsl代碼生成

    只要entity類和啟動類按上面方式加上注解,然后使用命令:

    gradle build -x test

    就可以在build目錄下生成Q文件

    總結

    以上是生活随笔為你收集整理的springboot-jpa-querydsl的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。