-
Notifications
You must be signed in to change notification settings - Fork 1
/
MongoMapper.java
68 lines (57 loc) · 1.61 KB
/
MongoMapper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.mobvoi.data.utils;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.mongodb.client.MongoCursor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
/**
* Created by lichao on 2017/7/31.
*/
@Slf4j
public class MongoMapper<T> {
private static final Gson gson = new Gson();
public static <T> List<T> getModelListFromMongo(MongoCursor<Document> resultCursor,
ParameterizedType type) {
List<T> results = Lists.newArrayList();
try {
while (resultCursor.hasNext()) {
results.add(gson.fromJson(gson.toJson(resultCursor.next()), type));
}
} catch (Exception ex) {
log.error("getModelListFromMongo error: ", ex);
} finally {
resultCursor.close();
}
return results;
}
public static <T> Optional<T> getModelFromMongo(MongoCursor<Document> resultCursor,
ParameterizedType type) {
try {
if (resultCursor.hasNext()) {
return Optional.of(gson.fromJson(gson.toJson(resultCursor.next()), type));
}
} catch (Exception ex) {
log.error("getModelFromMongo error: ", ex);
} finally {
resultCursor.close();
}
return null;
}
public static ParameterizedType type(final Class raw, final Type... args) {
return new ParameterizedType() {
public Type getRawType() {
return raw;
}
public Type[] getActualTypeArguments() {
return args;
}
public Type getOwnerType() {
return null;
}
};
}
}