// 这个查询出来所有符合条件的数据集合,速度很慢,主要是这种方式的数据映射过程太过耗时:
public List<MineUserDetail> findListByGid(String groupId) {
Query query = new Query(Criteria.where("groupId").is(groupId).and("everyId").is(0L).and("status").is(0));
return mongoTemplate.find(query, MineUserDetail.class);
}
//这种方式,MongoCursor,他是mongo的游标,不是立即从数据库中取出数据,而是在我们使用时才会取出数据。这时候需要我们手动映射数据
public List<MineUserDetail> findListByGid(String groupId) {
DBObject query = new BasicDBObject();
query.put("groupId",groupId);
query.put("everyId",0);
query.put("status",0);
MongoCursor<Document> mongoCursor = mongoTemplate.getCollection("mine_user").find((Bson) query).iterator();
List<MineUserDetail> list = convertData(mongoCursor, MineUserDetail.class);
return list;
//利用反射+泛型,定义工具类
public <T> List<T> convertData(MongoCursor<Document> mongoCursor, Class<T> tClass){
List<T> list = new ArrayList<>();
Field[] fields = tClass.getDeclaredFields();
T t = null;
try {
while (mongoCursor.hasNext()) {
t = tClass.newInstance();
Document obj = mongoCursor.next();
for (Field field : fields) {
field.setAccessible(true);
String name = field.getName();
if (ObjectUtils.isNotEmpty(obj.get(name))){
field.set(t,obj.get(name));
list.add(t);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
return list;
分页工具类:
public static <T> List<T> page(List<T> datalist, Integer page, Integer size) {
List<T> list = new ArrayList<T>();
if (datalist != null && datalist.size() > 0) {
int cuurIdx = (page > 1 ? (page - 1) * size : 0);
for (int i = 0; i < size && i < datalist.size() - cuurIdx; i++) {
T user = datalist.get(cuurIdx + i);
list.add(user);
return list;