zoukankan      html  css  js  c++  java
  • spring boot 自定义sql分页查询

     @Override
        public <T> Page<T> pageSQL(@Nonnull String sql, @Nonnull Pageable pageable, @Nonnull Class<T> clazz) {
            Long totalCount = totalCount(sql);
            NativeQuery nativeQuery = (NativeQuery) entityManager.createNativeQuery(sql);
            this.addScalar(nativeQuery, clazz);
            Query query = nativeQuery.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(clazz));
            query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
            query.setMaxResults(pageable.getPageSize());
            List<T> list = query.getResultList();
            return new PageImpl<>(list, pageable, totalCount);
        }
    
        /**
         * 添加 字段类型
         * @param nativeQuery sql查询语句
         * @param clazz 类
         */
        private void addScalar(NativeQuery nativeQuery, @Nonnull Class clazz) {
            for (Field field : clazz.getDeclaredFields()) {
                nativeQuery.addScalar(field.getName(), CLASS_TYPE_MAP.get(field.getType()));
            }
            if (clazz.getSuperclass() != null) {
                addScalar(nativeQuery, clazz.getSuperclass());
            }
        }
    
        @Override
        public Long totalCount(@Nonnull String sql) {
            sql = "select count(1) from (" + sql + ") countAlias";
            NativeQuery query = (NativeQuery) entityManager.createNativeQuery(sql);
            BigInteger bigInteger = (BigInteger) query.uniqueResult();
            return bigInteger.longValue();
        }
    
        public static final Map<Class<?>, Type> CLASS_TYPE_MAP = new HashMap<>();
    
        static {
            CLASS_TYPE_MAP.put(Integer.class, StandardBasicTypes.INTEGER);
            CLASS_TYPE_MAP.put(Long.class, StandardBasicTypes.LONG);
            CLASS_TYPE_MAP.put(Float.class, StandardBasicTypes.FLOAT);
            CLASS_TYPE_MAP.put(Double.class, StandardBasicTypes.DOUBLE);
            CLASS_TYPE_MAP.put(BigDecimal.class, StandardBasicTypes.BIG_DECIMAL);
            CLASS_TYPE_MAP.put(String.class, StandardBasicTypes.STRING);
            CLASS_TYPE_MAP.put(LocalDate.class, LocalDateType.INSTANCE);
            CLASS_TYPE_MAP.put(LocalDateTime.class, LocalDateTimeType.INSTANCE);
            CLASS_TYPE_MAP.put(LocalTime.class, LocalTimeType.INSTANCE);
        }
  • 相关阅读:
    10.28
    10.29
    11.05周四
    数据库增删改查
    11.03Tuesday
    11.10
    连接数据库
    10.30
    11.04周三
    10.27
  • 原文地址:https://www.cnblogs.com/shaolixin/p/10791796.html
Copyright © 2011-2022 走看看