springboot整合mongodb实现增删改查

释放双眼,带上耳机,听听看~!

引入jar包


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1       <!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver -->
2       <dependency>
3           <groupId>org.mongodb</groupId>
4           <artifactId>mongodb-driver</artifactId>
5           <version>3.4.3</version>
6       </dependency>
7       <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-mongodb -->
8       <dependency>
9           <groupId>org.springframework.boot</groupId>
10          <artifactId>spring-boot-starter-data-mongodb</artifactId>
11          <version>1.2.5.RELEASE</version>
12      </dependency>
13      <dependency>
14          <groupId>com.spring4all</groupId>
15          <artifactId>mongodb-plus-spring-boot-starter</artifactId>
16          <version>1.0.0.RELEASE</version>
17      </dependency>
18

使用了mongo连接池,mongodb-plus

配置文件


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
1Mongodb
2库名
3spring.data.mongodb.database=atm-ep
4spring.data.mongodb.host=192.168.1.49
5spring.data.mongodb.port=27017
6spring.http.encoding.force-request=true
7spring.mandatory-file-encoding=UTF-8
8#用户名和密码 有的话需要加上
9#spring.data.mongodb.username=atm_ep
10#spring.data.mongodb.password=atm_ep
11
12
13spring.data.mongodb.option.min-connection-per-host=0
14spring.data.mongodb.option.max-connection-per-host=100
15spring.data.mongodb.option.threads-allowed-to-block-for-connection-multiplier=5
16spring.data.mongodb.option.server-selection-timeout=30000
17spring.data.mongodb.option.max-wait-time=120000
18spring.data.mongodb.option.max-connection-idle-time=0
19spring.data.mongodb.option.max-connection-life-time=0
20spring.data.mongodb.option.connect-timeout=10000
21spring.data.mongodb.option.socket-timeout=0
22
23spring.data.mongodb.option.socket-keep-alive=false
24spring.data.mongodb.option.ssl-enabled=false
25spring.data.mongodb.option.ssl-invalid-host-name-allowed=false
26spring.data.mongodb.option.always-use-m-beans=false
27
28spring.data.mongodb.option.heartbeat-socket-timeout=20000
29spring.data.mongodb.option.heartbeat-connect-timeout=20000
30spring.data.mongodb.option.min-heartbeat-frequency=500
31spring.data.mongodb.option.heartbeat-frequency=10000
32spring.data.mongodb.option.local-threshold=15
33

启动类使用注解@EnableMongoPlus


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1@EnableMongoPlus
2public class App  {
3
4   @RequestMapping("/ep/")
5   String home() {
6       return "redirect:index.html";
7   }
8  
9  
10  public static void main(String[] args) throws Exception {
11      SpringApplication.run(App.class, args);
12    }
13
14}
15

自己写了个简单的工具类,项目中为了灵活使用,数据结构存为json对象


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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
1
2
3import com.alibaba.fastjson.JSONArray;
4import com.alibaba.fastjson.JSONObject;
5
6import org.apache.commons.lang3.StringUtils;
7import org.springframework.beans.factory.annotation.Autowired;
8import org.springframework.data.domain.Sort;
9import org.springframework.data.mongodb.core.BulkOperations;
10import org.springframework.data.mongodb.core.MongoTemplate;
11import org.springframework.data.mongodb.core.mapreduce.GroupBy;
12import org.springframework.data.mongodb.core.mapreduce.GroupByResults;
13import org.springframework.data.mongodb.core.query.Criteria;
14import org.springframework.data.mongodb.core.query.Query;
15import org.springframework.data.mongodb.core.query.Update;
16import org.springframework.stereotype.Component;
17
18import java.util.*;
19
20@Component
21public class Mongodb {
22
23  @Autowired
24  private MongoTemplate mongoTemplate;
25
26 
27 
28
29  /**
30   * 根据ID查询
31   * @param id ID
32   * @param tableName 表名
33   * @return
34   */
35  public JSONObject findById(String id, String tableName) {
36      Query query = new Query();
37      query.addCriteria(Criteria.where("ID").is(id));
38      return findOne(query, tableName);
39  }
40
41  /**
42   * 查询单条数据
43   *
44   * @param query
45   *            查询条件
46   * @param tableName
47   *            表名
48   */
49  public JSONObject findOne(Query query, String tableName) {
50      return mongoTemplate.findOne(query, JSONObject.class, tableName);
51  }
52
53  /**
54   * 查询表中所有数据
55   *
56   * @param tableName
57   *            表名
58   */
59  public List<JSONObject> findAll(String tableName) {
60      return mongoTemplate.findAll(JSONObject.class, tableName);
61  }
62
63  /**
64   * 条件查询 只支持and的关系
65   *
66   * @param map
67   *            条件 key=id value=1 查询id为1的数据
68   * @param tableName
69   *            表名
70   * @return
71   */
72  public List<JSONObject> find(Map<String, Object> map, String tableName) {
73      Query quey = new Query();
74      for (Map.Entry<String, Object> m : map.entrySet()) {
75          String key = m.getKey();
76          Object value = m.getValue();
77          quey.addCriteria(Criteria.where(key).is(value));
78      }
79      return find(quey, tableName);
80  }
81
82  /**
83   * 查询表是否存在
84   *
85   * @param tableName
86   * @return
87   */
88  public boolean findTable(String tableName) {
89      return mongoTemplate.exists(new Query(), tableName);
90  }
91
92  /**
93   * 条件排序查询
94   *
95   * @param map
96   *            参数
97   * @param tableName
98   *            表名
99   * @param sort
100  *            排序字段
101  * @return
102  */
103 public List<JSONObject> findSortList(Map<String, Object> map, String tableName, String sort) {
104     Query quey = new Query();
105     for (Map.Entry<String, Object> m : map.entrySet()) {
106         String key = m.getKey();
107         Object value = m.getValue();
108         quey.addCriteria(Criteria.where(key).is(value));
109     }
110     quey.with(new Sort(Sort.Direction.ASC, sort));
111     return find(quey, tableName);
112 }
113
114
115 /**
116  * 新增一条数据
117  *
118  * @param json
119  *            数据
120  * @param tableName
121  *            表名字
122  */
123 public void save(JSONObject json, String tableName) {
124     mongoTemplate.save(json, tableName);
125 }
126
127 /**
128  * 批量插入
129  *
130  * @param list
131  *            数据集合
132  * @param tableName
133  *            表名
134  */
135 public void batchSave(List<JSONObject> list, String tableName) {
136     if (list != null && list.size() > 0) {
137         // BulkMode.UNORDERED:表示并行处理,遇到错误时能继续执行不影响其他操作;BulkMode.ORDERED:表示顺序执行,遇到错误时会停止所有执行
138         BulkOperations ops = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, tableName);
139         ops.insert(list);
140         ops.execute();
141     }
142 }
143
144 /**
145  * 更新符条件的第一条记录数据
146  *
147  * @param query
148  *            更新条件
149  * @param update
150  *            更新的属性和值
151  * @param tableName
152  *            表名
153  * @return 更新状态
154  */
155 public boolean update(Query query, Update update, String tableName) {
156     return mongoTemplate.updateFirst(query, update, tableName).isUpdateOfExisting();
157 }
158
159 /**
160  * 更新符合条件的所有数据
161  *
162  * @param query
163  *            条件
164  * @param update
165  *            更新的属性和值
166  * @param tableName
167  *            表名
168  * @return 更新状态
169  */
170 public boolean updateMulti(Query query, Update update, String tableName) {
171     return mongoTemplate.updateMulti(query, update, tableName).isUpdateOfExisting();
172 }
173
174 /**
175  * 条件查询
176  *
177  * @param query
178  *            条件
179  * @param tableName
180  *            表名
181  */
182 public List<JSONObject> find(Query query, String tableName) {
183     return mongoTemplate.find(query, JSONObject.class, tableName);
184 }
185
186 /**
187  * 删除指定的数据
188  *
189  * @param json
190  * @param tableName
191  *            表名
192  * @return
193  */
194 public int delete(JSONObject json, String tableName) {
195     return mongoTemplate.remove(json, tableName).getN();
196 }
197
198 /**
199  * 根据条件删除
200  *
201  * @param query
202  *            条件
203  * @param tableName
204  *            表名
205  * @return 受影响的文档数
206  */
207 public int delete(Query query, String tableName) {
208     return mongoTemplate.remove(query, tableName).getN();
209 }
210
211 /**
212  * 数量
213  */
214 public long count(Query query, String tableName) {
215     return mongoTemplate.count(query, tableName);
216 }
217
218 /**
219  * group by
220  */
221 public GroupByResults<JSONObject> group(Criteria criteria, String inputCollectionName, GroupBy groupBy,
222         Class<JSONObject> entityClass) {
223     return mongoTemplate.group(criteria, inputCollectionName, groupBy, entityClass);
224 }
225
226
227 /**
228  * 通过ID删除
229  *
230  * @param ID
231  * @param tableName
232  * @return
233  */
234 public int deleteByID(String ID, String tableName) {
235     Query query = new Query();
236     query.addCriteria(Criteria.where("ID").is(ID));
237     return delete(query, tableName);
238 }
239
240
241    /**
242     * 删除表
243     * @param tableName
244     * @return
245     */
246    public  void deleteTable(String tableName){
247        mongoTemplate.dropCollection(tableName);
248    }
249    
250}
251
252

库中数据存储结构类似下面的(使用mongo客户端为Studio 3T ,挺好用的 需要破解一下)

springboot整合mongodb实现增删改查

使用mongodb最大的好处是可以很随意的扩充列,因为存的是json对象 ,所以数据结构很灵活,不过mongodb写复杂sql查询是挺麻烦的,最好把数据平铺进去,不要写复杂sql查询,而且mongo本身是文件存储数据库,上传文件速度还是挺快的。

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++ explicit关键字

2022-1-11 12:36:11

安全技术

这篇文章很好的诠释了为什么安全框架如此重要?

2016-12-26 16:13:03

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索