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);
    }

 

posted @ 2019-04-29 17:34  生活这把杀猪刀  阅读(2851)  评论(0编辑  收藏  举报