SpringDataJpa分页查询

法一(本地sql查询,注意表名啥的都用数据库中的名称,适用于特定数据库的查询)


public interface UserRepository extends JpaRepository<User, Long> {

  @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
    countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
    nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);

@Query(value = "SELECT u  FROM Users u WHERE u.username like %:username%")
List<User> findByName(@Param("username") String  username);
}

 

法二(jpa已经实现的分页接口,适用于简单的分页查询)


public interface PagingAndSortingRepository<T, ID extends Serializable>
  extends CrudRepository<T, ID> {

  Iterable<T> findAll(Sort sort);

  Page<T> findAll(Pageable pageable);
}

Accessing the second page of User by a page size of 20 you could simply do something like this:

PagingAndSortingRepository<User, Long> repository = // … get access to a bean
Page<User> users = repository.findAll(new PageRequest(1, 20));


User findFirstByOrderByLastnameAsc();

User findTopByOrderByAgeDesc();

Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);

Slice<User> findTop3ByLastname(String lastname, Pageable pageable);

List<User> findFirst10ByLastname(String lastname, Sort sort);

List<User> findTop10ByLastname(String lastname, Pageable pageable);

 


//service
 Sort sort = new Sort(Sort.Direction.DESC,"createTime"); //创建时间降序排序
 Pageable pageable = new PageRequest(pageNumber,pageSize,sort);
 this.depositRecordRepository.findAllByUserIdIn(userIds,pageable);

//repository
Page<DepositRecord> findAllByUserIdIn(List<Long> userIds,Pageable pageable);

 

 

法三(Query注解,hql语局,适用于查询指定条件的数据)

 @Query(value = "select b.roomUid from RoomBoard b where b.userId=:userId and b.lastBoard=true order by  b.createTime desc")
    Page<String> findRoomUidsByUserIdPageable(@Param("userId") long userId, Pageable pageable);
Pageable pageable = new PageRequest(pageNumber,pageSize);
Page<String> page = this.roomBoardRepository.findRoomUidsByUserIdPageable(userId,pageable);
List<String> roomUids = page.getContent();

可以自定义整个实体(Page<User>),也可以查询某几个字段(Page<Object[]>),和原生sql几乎一样灵活。

 

法四(扩充findAll,适用于动态sql查询)

public interface UserRepository extends JpaRepository<User, Long> {

    Page<User> findAll(Specification<User> spec, Pageable pageable);
} 

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public Page<User> getUsersPage(PageParam pageParam, String nickName) {
        //规格定义
        Specification<User> specification = new Specification<User>() {

            /**
             * 构造断言
             * @param root 实体对象引用
             * @param query 规则查询对象
             * @param cb 规则构建对象
             * @return 断言
             */
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>(); //所有的断言
                if(StringUtils.isNotBlank(nickName)){ //添加断言
                    Predicate likeNickName = cb.like(root.get("nickName").as(String.class),nickName+"%");
                    predicates.add(likeNickName);
                }
                return cb.and(predicates.toArray(new Predicate[0]));
            }
        };
        //分页信息
        Pageable pageable = new PageRequest(pageParam.getPage()-1,pageParam.getLimit()); //页码:前端从1开始,jpa从0开始,做个转换
        //查询
        return this.userRepository.findAll(specification,pageable);
    }

}

 

法五(使用entityManager,适用于动态sql查询)


@Service
@Transactional
public class IncomeService{ /** * 实体管理对象 */ @PersistenceContext EntityManager entityManager; public Page<IncomeDaily> findIncomeDailysByPage(PageParam pageParam, String cpId, String appId, Date start, Date end, String sp) { StringBuilder countSelectSql = new StringBuilder(); countSelectSql.append("select count(*) from IncomeDaily po where 1=1 "); StringBuilder selectSql = new StringBuilder(); selectSql.append("from IncomeDaily po where 1=1 "); Map<String,Object> params = new HashMap<>(); StringBuilder whereSql = new StringBuilder(); if(StringUtils.isNotBlank(cpId)){ whereSql.append(" and cpId=:cpId "); params.put("cpId",cpId); } if(StringUtils.isNotBlank(appId)){ whereSql.append(" and appId=:appId "); params.put("appId",appId); } if(StringUtils.isNotBlank(sp)){ whereSql.append(" and sp=:sp "); params.put("sp",sp); } if (start == null) { start = DateUtil.getStartOfDate(new Date()); } whereSql.append(" and po.bizDate >= :startTime"); params.put("startTime", start); if (end != null) { whereSql.append(" and po.bizDate <= :endTime"); params.put("endTime", end); } String countSql = new StringBuilder().append(countSelectSql).append(whereSql).toString(); Query countQuery = this.entityManager.createQuery(countSql,Long.class); this.setParameters(countQuery,params); Long count = (Long) countQuery.getSingleResult(); String querySql = new StringBuilder().append(selectSql).append(whereSql).toString(); Query query = this.entityManager.createQuery(querySql,IncomeDaily.class); this.setParameters(query,params); if(pageParam != null){ //分页 query.setFirstResult(pageParam.getStart()); query.setMaxResults(pageParam.getLength()); } List<IncomeDaily> incomeDailyList = query.getResultList(); if(pageParam != null) { //分页 Pageable pageable = new PageRequest(pageParam.getPage(), pageParam.getLength()); Page<IncomeDaily> incomeDailyPage = new PageImpl<IncomeDaily>(incomeDailyList, pageable, count); return incomeDailyPage; }else{ //不分页 return new PageImpl<IncomeDaily>(incomeDailyList); } } /** * 给hql参数设置值 * @param query 查询 * @param params 参数 */ private void setParameters(Query query,Map<String,Object> params){ for(Map.Entry<String,Object> entry:params.entrySet()){ query.setParameter(entry.getKey(),entry.getValue()); } }
}
 
 
 
 
package com.ukefu.webim.service.es;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;

import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder.Operator;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import com.ukefu.webim.web.model.EntCustomer;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Repository
public class EntCustomerRepositoryImpl implements EntCustomerEsCommonRepository {

    @PersistenceContext
    EntityManager entityManager;

    /**
     * @param nameOrPhone 判断 根据手机或者姓名进行模糊查询  名称 手机  不限
     * @param entCustomer 根据 etype 类型 精确查询
     *                    phone 手机对应使用手机模糊查询
     *                    name 名字对应使用名字模糊查询
     *                    province 省份 精确查询
     *                    city 城市 精确查询
     *                    maturity 成熟度 精确查询
     *                    creater  创建者 必备查询条件
     *                    shares 是否共享 必备查询条件
     *                    orgi  组织 必备查询条件
     *                    ekind 客户类型
     * @return
     */
    @Override
    public Page<EntCustomer> findByCreaterAndSharesAndOrgi(String nameOrPhone, EntCustomer entCustomer, Pageable page) {

        StringBuilder countSelectSql = new StringBuilder();
        countSelectSql.append("select count(*) from EntCustomer po where 1=1 ");
        StringBuilder selectSql = new StringBuilder();
        selectSql.append("from EntCustomer po where 1=1 ");
        Map<String, Object> params = new HashMap<>();
        StringBuilder whereSql = new StringBuilder();

        if (!StringUtils.isBlank(entCustomer.getEkind())) {
            whereSql.append(" and ekind=:ekind");
            params.put("ekind", entCustomer.getEkind());
        }

        if (!StringUtils.isBlank(entCustomer.getOrgi())) {
            whereSql.append(" and orgi=:orgi");
            params.put("orgi", entCustomer.getOrgi());
        }

        if (!StringUtils.isBlank(entCustomer.getEtype())) {
            whereSql.append(" and etype=:etype");
            params.put("etype", entCustomer.getEtype());
        }

        if (!StringUtils.isBlank(entCustomer.getProvince())) {
            whereSql.append(" and province=:province");
            params.put("province", entCustomer.getProvince());
        }

        if (!StringUtils.isBlank(entCustomer.getCity())) {
            whereSql.append(" and city=:city");
            params.put("city", entCustomer.getCity());
        }

        if (!StringUtils.isBlank(entCustomer.getMaturity())) {
            whereSql.append(" and maturity=:maturity");
            params.put("maturity", entCustomer.getMaturity());
        }

        whereSql.append(" and (creater=:creater or shares=:shares)");
        params.put("creater", entCustomer.getCreater());
        params.put("shares", "all");

        if (StringUtils.isNotBlank(entCustomer.getName())) {
//			根据手机或名字模糊查询
            if (Objects.equals(nameOrPhone, "不限")) {
                whereSql.append(" and (name like :name or phone like :phone)");
                params.put("name", "%"+entCustomer.getName()+"%");
                params.put("phone", "%"+entCustomer.getName()+"%");

//根据手机模糊查询
            } else if (Objects.equals(nameOrPhone, "手机")) {
                whereSql.append(" and  phone like :phone");
                params.put("phone", "%"+entCustomer.getName()+"%");

//根据名字模糊查询
            } else {
                whereSql.append(" and name like :name ");
                params.put("name", "%"+entCustomer.getName()+"%");

            }

        }

        String countSql = new StringBuilder().append(countSelectSql).append(whereSql).toString();
        Query countQuery = this.entityManager.createQuery(countSql, Long.class);
        this.setParameters(countQuery, params);
        Long count = (Long) countQuery.getSingleResult();
        String querySql = new StringBuilder().append(selectSql).append(whereSql).toString();
        Query query = this.entityManager.createQuery(querySql, EntCustomer.class);
        this.setParameters(query, params);
        if (page != null) { //分页
            query.setFirstResult(page.getPageSize() * page.getPageNumber());
            query.setMaxResults(page.getPageSize());
        }
        List<EntCustomer> entCustomerList = query.getResultList();
        Page<EntCustomer> entCustomerPage = new PageImpl<EntCustomer>(entCustomerList, page, count);
        return entCustomerPage;

    }

    /**
     * 给hql参数设置值
     *
     * @param query  查询
     * @param params 参数
     */
    private void setParameters(Query query, Map<String, Object> params) {
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            query.setParameter(entry.getKey(), entry.getValue());
        }
    }
}


猜你喜欢

转载自blog.csdn.net/zsj777/article/details/80535971