{{announcement.body}}
{{announcement.title}}

Sprint Boot, REST, MongoDB POC

DZone 's Guide to

Sprint Boot, REST, MongoDB POC

In this article, I’m going to cover Spring boot, Rest, and Mongo DB applications.

· Microservices Zone ·
Free Resource

Spring Boot + Rest + Mongo DB POC

Spring Boot

Spring boot is one of the hot technologies in the market that provides all on-demand libraries to make easy of developer work.  When I look back journey of Sprint from 3.x to Spring boot 2.x, there are a lot of changes and flexibilities provided by the framework. Spring boot bootstraps the application development process. In this article, I’m going to cover Spring boot, Rest, and Mongo DB application.

Mongo DB

Mongo DB is a document database, you can create data in different formats and persist JSON directly into Mongo DB.   

Scope

Develop rest APIs for Quotes services which should provide all CURD operations on QuoteServiceAPI.  I intend to keep it as simple as possible to make Everyone understands easily. Once you understand the blow then you can make however you want.  

Technology Stack: Spring Boot 2.2.0, Mongo DB, Java 8 and Spring Rest

CodeBase

 Go to start.spring.io/ and initialize the starter dependencies mentioned below. 

POM.XML

Code Structure
code structure

Java
 




x
351


1
 
          
2
Repository:
3
QuotesRepository.java (I)
4
package com.mongodb.starter.repositories;
5
import static com.mongodb.client.model.Filters.eq;
6
import java.util.ArrayList;
7
import java.util.List;
8
import org.bson.types.ObjectId;
9
import org.springframework.stereotype.Repository;
10
import com.mongodb.starter.models.Quotes;
11
/* 
12
 * author : Rajesh Thokala
13
 * date : 29/05/2020
14
 */
15
@Repository
16
public interface QuotesRepository {
17
    Quotes save(Quotes quotes);
18
 
          
19
    List<Quotes> saveAll(List<Quotes> quotes);
20
 
          
21
    List<Quotes> findAll();
22
 
          
23
    List<Quotes> findAll(List<String> ids);
24
 
          
25
    Quotes findOne(String id);
26
 
          
27
    long count();
28
 
          
29
    long delete(String id);
30
 
          
31
    long delete(List<String> ids);
32
 
          
33
    long deleteAll();
34
 
          
35
    Quotes update(Quotes quotes);
36
 
          
37
    long update(List<Quotes> quotess);
38
    List<Quotes> finAllByType(String type);
39
    /*added to find by type **/
40
     List<Quotes> finByType(String type);
41
        public List<Quotes> finAllByAuthor(String author);
42
        /*added to find by type **/
43
            List<Quotes> finByAuthor(String author);
44
     
45
 
          
46
}
47
MongoDBQuoteRepository.java©
48
 
          
49
package com.mongodb.starter.repositories;
50
import static com.mongodb.client.model.Filters.eq;
51
import static com.mongodb.client.model.Filters.in;
52
import static com.mongodb.client.model.ReturnDocument.AFTER;
53
import java.util.ArrayList;
54
import java.util.List;
55
import java.util.stream.Collectors;
56
import javax.annotation.PostConstruct;
57
import org.bson.BsonDocument;
58
import org.bson.types.ObjectId;
59
import org.springframework.beans.factory.annotation.Autowired;
60
import org.springframework.stereotype.Repository;
61
import com.mongodb.ReadConcern;
62
import com.mongodb.ReadPreference;
63
import com.mongodb.TransactionOptions;
64
import com.mongodb.WriteConcern;
65
import com.mongodb.client.ClientSession;
66
import com.mongodb.client.MongoClient;
67
import com.mongodb.client.MongoCollection;
68
import com.mongodb.client.model.FindOneAndReplaceOptions;
69
import com.mongodb.client.model.ReplaceOneModel;
70
import com.mongodb.client.model.WriteModel;
71
import com.mongodb.starter.models.Quotes;
72
/* 
73
 * author : Rajesh Thokala
74
 * date : 29/05/2020
75
 */
76
@Repository
77
public class MongoDBQuoteRepository implements QuotesRepository {
78
    private static final TransactionOptions txnOptions = TransactionOptions.builder()
79
            .readPreference(ReadPreference.primary())
80
            .readConcern(ReadConcern.MAJORITY)
81
            .writeConcern(WriteConcern.MAJORITY)
82
            .build();
83
@Autowired
84
private MongoClient client;
85
private MongoCollection<Quotes> quotesCollection;
86
int count=0;
87
@PostConstruct
88
void init() {
89
    quotesCollection = client.getDatabase("test").getCollection("quotes", Quotes.class);
90
}
91
    @Override
92
    public Quotes save(Quotes quote) {
93
           quote.setId(new ObjectId());
94
           quotesCollection.insertOne(quote);
95
            return quote;
96
        
97
    }
98
 
          
99
    @Override
100
    public List<Quotes> saveAll(List<Quotes> quotes) {
101
          try (ClientSession clientSession = client.startSession()) {
102
                return clientSession.withTransaction(() -> {
103
                    quotes.forEach(p -> p.setId(new ObjectId()));
104
                    quotesCollection.insertMany(clientSession, quotes);
105
                    return quotes;
106
                }, txnOptions);
107
            }
108
        }
109
/*added to find all by type **/
110
    @Override
111
    public List<Quotes> finAllByAuthor(String author){
112
        
113
        return quotesCollection.find(eq("author",author)).into(new ArrayList<>());
114
    //  return quotesCollection.find(eq("author",author)).batchSize(3).into(new ArrayList<>());
115
    }
116
    /*added to find by type **/
117
    @Override
118
    public List<Quotes> finByAuthor(String author){
119
        List<Quotes> quoteList= quotesCollection.find(eq("author",author)).into(new ArrayList<>());
120
            List<Quotes> newList=new ArrayList<>();
121
        for(int i=count;i<count+3&&i<quoteList.size();i++) {
122
            newList.add(quoteList.get(i));
123
        }
124
        return newList;
125
    }
126
    
127
    /*added to find all by type **/
128
    @Override
129
    public List<Quotes> finAllByType(String type){
130
        
131
        return quotesCollection.find(eq("type",type)).into(new ArrayList<>());
132
         
133
    }
134
    /*added to find by type **/
135
    @Override
136
    public List<Quotes> finByType(String type){
137
    List<Quotes> quoteList= quotesCollection.find(eq("type",type)).into(new ArrayList<>());
138
    List<Quotes> newList=new ArrayList<>();
139
    for(int i=count;i<count+3&&i<quoteList.size();i++) {
140
        newList.add(quoteList.get(i));
141
    }
142
    return newList;
143
    }
144
    @Override
145
    public List<Quotes> findAll() {
146
        // TODO Auto-generated method stub
147
        return  quotesCollection.find().into(new ArrayList<>());
148
    }
149
 
          
150
    @Override
151
    public List<Quotes> findAll(List<String> ids) {
152
        // TODO Auto-generated method stub
153
        return quotesCollection.find(in("_id", mapToObjectIds(ids))).into(new ArrayList<>());
154
    }
155
 
          
156
    @Override
157
    public Quotes findOne(String id) {
158
        // TODO Auto-generated method stub
159
        return quotesCollection.find(eq("_id", new ObjectId(id))).first();
160
    }
161
 
          
162
    @Override
163
    public long count() {
164
        // TODO Auto-generated method stub
165
        return quotesCollection.countDocuments();
166
    }
167
 
          
168
    @Override
169
    public long delete(String id) {
170
        // TODO Auto-generated method stub
171
        return quotesCollection.deleteOne(eq("_id", new ObjectId(id))).getDeletedCount();
172
    }
173
 
          
174
    @Override
175
    public long delete(List<String> ids) {
176
        // TODO Auto-generated method stub
177
         try (ClientSession clientSession = client.startSession()) {
178
                return clientSession.withTransaction(
179
                        () -> quotesCollection.deleteMany(clientSession, in("_id", mapToObjectIds(ids))).getDeletedCount(),
180
                        txnOptions);
181
            }
182
    }
183
 
          
184
    @Override
185
    public long deleteAll() {
186
        // TODO Auto-generated method stub
187
         try (ClientSession clientSession = client.startSession()) {
188
                return clientSession.withTransaction(
189
                        () -> quotesCollection.deleteMany(clientSession, new BsonDocument()).getDeletedCount(), txnOptions);
190
            }
191
    }
192
 
          
193
    @Override
194
    public Quotes update(Quotes quotes) {
195
        // TODO Auto-generated method stub
196
        FindOneAndReplaceOptions options = new FindOneAndReplaceOptions().returnDocument(AFTER);
197
        return quotesCollection.findOneAndReplace(eq("_id", quotes.getId()), quotes, options);
198
    }
199
 
          
200
    @Override
201
    public long update(List<Quotes> quotes) {
202
        // TODO Auto-generated method stub
203
          List<WriteModel<Quotes>> writes = quotes.stream()
204
                  .map(p -> new ReplaceOneModel<>(eq("_id", p.getId()), p))
205
                  .collect(Collectors.toList());
206
                try (ClientSession clientSession = client.startSession()) {
207
                return clientSession.withTransaction(
208
                () -> quotesCollection.bulkWrite(clientSession, writes).getModifiedCount(), txnOptions);
209
                }
210
    }
211
     private List<ObjectId> mapToObjectIds(List<String> ids) {
212
            return ids.stream().map(ObjectId::new).collect(Collectors.toList());
213
        }
214
}
215
 
          
216
 
          
217
Controller:
218
QuotesController.Java
219
 
          
220
package com.mongodb.starter.controllers;
221
import static java.util.Arrays.asList;
222
import java.util.List;
223
import org.slf4j.Logger;
224
import org.slf4j.LoggerFactory;
225
import org.springframework.http.HttpStatus;
226
import org.springframework.http.ResponseEntity;
227
import org.springframework.web.bind.annotation.DeleteMapping;
228
import org.springframework.web.bind.annotation.ExceptionHandler;
229
import org.springframework.web.bind.annotation.GetMapping;
230
import org.springframework.web.bind.annotation.PathVariable;
231
import org.springframework.web.bind.annotation.PostMapping;
232
import org.springframework.web.bind.annotation.PutMapping;
233
import org.springframework.web.bind.annotation.RequestBody;
234
import org.springframework.web.bind.annotation.RequestMapping;
235
import org.springframework.web.bind.annotation.ResponseStatus;
236
import org.springframework.web.bind.annotation.RestController;
237
import com.mongodb.starter.models.Quotes;
238
import com.mongodb.starter.repositories.QuotesRepository;
239
/* 
240
 * author : Rajesh Thokala
241
 * date : 29/05/2020
242
 */
243
@RestController
244
@RequestMapping("/api")
245
public class QuotesController {
246
    private final static Logger LOGGER = LoggerFactory.getLogger(QuotesController.class);
247
    private final QuotesRepository quotesRepository;
248
 
          
249
    public QuotesController(QuotesRepository quotesRepository) {
250
        this.quotesRepository = quotesRepository;
251
    }
252
 
          
253
    @PostMapping("quote")
254
    @ResponseStatus(HttpStatus.CREATED)
255
    public Quotes postQuotes(@RequestBody Quotes quote) {
256
        return quotesRepository.save(quote);
257
    }
258
 
          
259
    @PostMapping("quotes")
260
    @ResponseStatus(HttpStatus.CREATED)
261
    public List<Quotes> postQuotess(@RequestBody List<Quotes> Quotes) {
262
        return quotesRepository.saveAll(Quotes);
263
    }
264
 
          
265
    @GetMapping("quotes")
266
    public List<Quotes> getQuotess() {
267
        return quotesRepository.findAll();
268
    }
269
 
          
270
    @GetMapping("quote/{id}")
271
    public ResponseEntity<Quotes> getQuotes(@PathVariable String id) {
272
        Quotes quotes = quotesRepository.findOne(id);
273
        if (quotes == null)
274
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
275
        return ResponseEntity.ok(quotes);
276
    }
277
    
278
    /** Getting list of quotes with type ***/
279
    @GetMapping("quotes/type/{all}")
280
    public List<Quotes> getQuotesByType(@PathVariable String all){ 
281
 
          
282
        return quotesRepository.finAllByType(all);
283
    }
284
 
          
285
    /** Getting quote with type  ***/
286
    
287
    @GetMapping("quote/type/{findOne}")
288
    public List<Quotes> getQuoteByType(@PathVariable String findOne){
289
        return quotesRepository.finByType(findOne);
290
    
291
    }
292
    
293
   
294
    /** Getting list of quotes with author  ***/
295
    @GetMapping("quotes/author/{all}")
296
    public List<Quotes> getQuotesByAuthor(@PathVariable String all){ 
297
            return quotesRepository.finAllByAuthor(all);
298
    }
299
    /** Getting quote with author  ***/
300
    @GetMapping("quote/author/{findOne}")
301
    public List<Quotes> getQuoteByAuthor(@PathVariable String findOne){
302
        return quotesRepository.finByAuthor(findOne);
303
            
304
    }
305
   
306
    @GetMapping("quotes/{ids}")
307
    public List<Quotes> getQuotess(@PathVariable String ids) {
308
        List<String> listIds = asList(ids.split(","));
309
        return quotesRepository.findAll(listIds);
310
    }
311
 
          
312
    @GetMapping("quotes/count")
313
    public Long getCount() {
314
        return quotesRepository.count();
315
    }
316
 
          
317
    @DeleteMapping("quotes/{id}")
318
    public Long deleteQuotes(@PathVariable String id) {
319
        return quotesRepository.delete(id);
320
    }
321
 
          
322
    @DeleteMapping("quotes/{ids}")
323
    public Long deleteQuotess(@PathVariable String ids) {
324
        List<String> listIds = asList(ids.split(","));
325
        return quotesRepository.delete(listIds);
326
    }
327
 
          
328
    @DeleteMapping("quotes")
329
    public Long deleteQuotess() {
330
        return quotesRepository.deleteAll();
331
    }
332
 
          
333
    @PutMapping("quote")
334
    public Quotes putQuote(@RequestBody Quotes quote) {
335
        return quotesRepository.update(quote);
336
    }
337
 
          
338
    @PutMapping("quotes")
339
    public Long putQuotes(@RequestBody List<Quotes> quotes) {
340
        return quotesRepository.update(quotes);
341
    }
342
 
          
343
  
344
    @ExceptionHandler(RuntimeException.class)
345
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
346
    public final Exception handleAllExceptions(RuntimeException e) {
347
        LOGGER.error("Internal server error.", e);
348
        return e;
349
    }
350
}
351
 
          



MongoDB
mongodb       

Get complete code from below GIT link https://github.com/rajeshjaava/SpringBoot-Rest-MongoDb.

Thanks for reading the article!

Topics:
java, microservices, mongodb, rest, springboot, springbootmicroservices

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}