Jpa 各种查询操作

2039859.jpg

前提是已经搭好了 JPA 的框架。。。。。

1.使用 JPAQueryFactory 进行查询操作

1.1简单查询

分页构造信息

package cn.superfw.genesis.common.core;

public class ApiPagination {

    /** 当前页码 */
    private Long page = 1L;
    /** 一页表示件数 */
    private Long limit = 10L;
    /** 总件数 */
    private Long count = 0L;

    public ApiPagination() {
    }

    public ApiPagination(Long page, Long limit, Long count) {
        if (page != null && page > 1L) {
            this.page = page;
        }
        if (limit != null && limit > 0L) {
            this.limit = limit;
        }
        if (count != null && count > 0L) {
            this.count = count;
        }
    }

    public ApiPagination(Long page, Long limit) {
        this.page = page;
        this.limit = limit;
    }

    public Long getOffset() {
        return (this.page - 1) * this.limit;
    }

    public Long getOffsetLimit() {
        if (getOffset() + getLimit() > getCount()) {
            return getCount();
        } else {
            return getOffset() + getLimit();
        }
    }

    /**
     * 获取 当前页码
     *
     * @return page 当前页码
     */
    public Long getPage() {
        return this.page;
    }

    /**
     * 设置 当前页码
     *
     * @param page 当前页码
     */
    public void setPage(Long page) {
        this.page = page;
    }

    /**
     * 获取 一页表示件数
     *
     * @return limit 一页表示件数
     */
    public Long getLimit() {
        return this.limit;
    }

    /**
     * 设置 一页表示件数
     *
     * @param limit 一页表示件数
     */
    public void setLimit(Long limit) {
        this.limit = limit;
    }

    /**
     * 获取 总件数
     *
     * @return count 总件数
     */
    public Long getCount() {
        return this.count;
    }

    /**
     * 设置 总件数
     *
     * @param count 总件数
     */
    public void setCount(Long count) {
        this.count = count;
    }
}

自定义返回类

package cn.superfw.genesis.common.core;

public class PlatformServiceResult<T> {

    /** 数据 */
    private T data;

    /** 分页构造器 */
    private ApiPagination pagination;

    /** 构造函数 */
    public PlatformServiceResult(T data, ApiPagination pagination) {
        super();
        this.data = data;
        this.pagination = pagination;
    }

    /**
     * @return the data
     */
    public T getData() {
        return data;
    }

    /**
     * @param data the data to set
     */
    public void setData(T data) {
        this.data = data;
    }

    /**
     * @return the pagination
     */
    public ApiPagination getPagination() {
        return pagination;
    }

    /**
     * @param pagination the pagination to set
     */
    public void setPagination(ApiPagination pagination) {
        this.pagination = pagination;
    }

}

UserRepositoryDsl

package cn.superfw.genesis.zs.repository;


import cn.superfw.genesis.zs.domain.UserEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface UserRepositoryDsl extends JpaRepository<UserEntity, Long>, QuerydslPredicateExecutor<UserEntity> {

    @Query(value="select * from user where (:name is null or name like %:name%) and (coalesce (:ageList,:isnull) is null or age in (:ageList))",
            countQuery="select * from user where (:name is null or name like %:name%) and (coalesce (:ageList,:isnull) is null or age in (:ageList))",nativeQuery=true)
    Page<UserEntity> getUserByDsl(@Param(value="name") String name,
                                  @Param(value = "ageList") List<Integer> ageList,
                                  @Param(value="isnull") Long isnull,
                                  Pageable pageable);
}

逻辑实现类

//需要用的 jar 包
import com.querydsl.jpa.impl.JPAQueryFactory;
////////////////////////////////////////////////////////////////////////////////
package cn.superfw.genesis.zs.service.Impl;

import cn.superfw.genesis.common.core.ApiPagination;
import cn.superfw.genesis.common.core.PlatformServiceResult;
import cn.superfw.genesis.zs.domain.QUserEntity;
import cn.superfw.genesis.zs.domain.UserEntity;
import cn.superfw.genesis.zs.repository.UserRepositoryDsl;
import cn.superfw.genesis.zs.service.UserService;
import cn.superfw.genesis.zs.vo.RunScheduleVo;
import cn.superfw.genesis.zs.vo.UserVo;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    JPAQueryFactory queryFactory;
    @Autowired
    UserRepositoryDsl userRepositoryDsl;


    /**
     * 动态条件查询 hql
     * @param id
     * @param name
     * @param age
     * @param money
     * @param createdTime
     * @return
     */
    @Override
    public PlatformServiceResult<List<UserEntity>> findUsers(Long id, String name, Integer age, Double money, Timestamp createdTime,Long page, Long limit) {
        QUserEntity qUserEntity = QUserEntity.userEntity;
        // 拼造查询条件
        BooleanExpression whereExp = qUserEntity.deleteStatus.eq(1);
        if (id != null){
            whereExp = whereExp.and(qUserEntity.id.eq(id));
        }
        //姓名模糊查询
        if(StringUtils.isNotEmpty(name)){
            whereExp = whereExp.and(qUserEntity.name.contains(name));
        }
        if (age != null){
            whereExp = whereExp.and(qUserEntity.age.eq(age));
        }
        if (money != null){
            whereExp = whereExp.and(qUserEntity.money.eq(money));
        }
        if (createdTime != null){
            whereExp = whereExp.and(qUserEntity.createdTime.eq(createdTime));
        }
        //查询所有(使用了上面自己拼接的查询条件)
        List<UserEntity> userEntities = queryFactory.selectFrom(qUserEntity).where(whereExp).fetch();

        //简单查询(查询 name 叫 周杰伦 的人)单个人 注:.fetch()结尾查询的是列表,.fetchFirst() 或 .fetchOne() 查询的是单个。
        UserEntity userEntity = queryFactory.selectFrom(qUserEntity).where(qUserEntity.name.eq("周杰伦")).fetchOne();

        //查询某一个字段(查询 id 为 1 的人的名字)
        String nName = queryFactory.select(qUserEntity.name).from(qUserEntity).where(qUserEntity.id.eq(id)).fetchFirst();

        //查询返回自定义实体类(select中的字段顺序需要和自定义实体类中我的构造器顺序一致)
        List<UserVo> userVos = queryFactory.select(Projections.constructor(UserVo.class,qUserEntity.id,qUserEntity.name,qUserEntity.age,qUserEntity.gender,qUserEntity.money))
                .from(qUserEntity).fetch();

        //分页查询
        //查询到的数据数量
        Long count = queryFactory.select(qUserEntity.id).from(qUserEntity).where(whereExp).fetchCount();
        // 分页控制信息构造
        ApiPagination pagination =  new ApiPagination(page == null ? 1 : page, limit == null ? 20 : limit,count);
        //查询数据
        List<UserEntity> data = queryFactory.selectFrom(qUserEntity).where(whereExp).offset(pagination.getOffset()).limit(pagination.getLimit()).fetch();

        return new PlatformServiceResult<List<UserEntity>>(data,pagination);
    }


    /**
     * 条件查询人类 sql
     * @param name
     * @param page
     * @param limit
     * @return
     */
    @Override
    public PlatformServiceResult<List<UserEntity>> findUsersForDSL(String name,List<Integer> ageList, Long page, Long limit) {
        //DSl中ageList判空时出错,所以自己定义了一个isnull
        Long isnull = null;

        if (ageList!=null){
            if (ageList.size()==0){
                ageList=null;
            }
        }

        if (page==null){
            page = Long.valueOf(0);
        }else {
            page = page - 1;
        }
        //构造分页查询
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page.intValue(),limit == null ? 20 : limit.intValue(),sort );
        Page<UserEntity> data = userRepositoryDsl.getUserByDsl(name,ageList,isnull,pageable);
        Long count = data.getTotalElements();
        ApiPagination pagination = new ApiPagination(page == null ? 1 : page, limit == null ? 20 : limit,count);
        return new PlatformServiceResult<List<UserEntity>>(data.getContent(),pagination);
    }


}


©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 226,333评论 6 524
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 97,345评论 3 411
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 173,869评论 0 370
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 61,897评论 1 305
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 70,790评论 6 404
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 54,288评论 1 318
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 42,449评论 3 433
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 41,579评论 0 282
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,092评论 1 329
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,080评论 3 352
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,192评论 1 362
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 37,767评论 5 354
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 43,491评论 3 342
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 33,860评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 35,070评论 1 278
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 50,793评论 3 385
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,218评论 2 369

推荐阅读更多精彩内容