All Downloads are FREE. Search and download functionalities are using the official Maven repository.

me.wuwenbin.modules.mongodb.dao.MongoDbTemplate Maven / Gradle / Ivy

There is a newer version: 1.11.0.RELEASE
Show newest version
package me.wuwenbin.modules.mongodb.dao;

import me.wuwenbin.modules.mongodb.pojo.PageParam;
import me.wuwenbin.modules.mongodb.support.page.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @see {@link MongoAccessor}
 * Created by wuwenbin on 2017/4/23.
 */
public class MongoDbTemplate extends MongoAccessor {

    public MongoDbTemplate(MongoTemplate mongoTemplate) {
        super(mongoTemplate);
    }

    @Override
    protected PageParam getPageParam(Page page) {
        if (page.isFirstSetted() && page.isPageSizeSetted()) {
            return new PageParam(page.getFirst(), page.getPageSize());
        }
        return new PageParam(0, 1);
    }


    /**
     * 根据查询条件来查找分页信息
     *
     * @param query
     * @param page
     * @param clazz
     * @param 
     * @return
     */
    public  Page findPageListBeanByQuery(Query query, Page page, Class clazz) {
        Assert.notNull(page, "分页信息不能为空");
        PageParam pageParam = getPageParam(page);
        query.skip(pageParam.getSkip()).limit(pageParam.getLimit());
        long count;
        if (page.isAutoCount()) {
            count = mongoTemplate.count(query, clazz);
            page.setTotalCount((int) count);
        }
        List list = findListBeanByQuery(query, clazz);
        page.setResult(list);
        return page;
    }

    /**
     * 按某字段排序查出page分页信息
     *
     * @param sortField
     * @param direction
     * @param page
     * @param clazz
     * @param 
     * @return
     */
    public  Page findPageListBeanBySort(String sortField, Sort.Direction direction, Page page, Class clazz) {
        Query query = new Query().with(new Sort(direction, sortField));
        return findPageListBeanByQuery(query, page, clazz);
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy