Commit 439cbe83 authored by Ravinder Pannala's avatar Ravinder Pannala

First Spring boot and MongoDB

parent 538cd8de
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.demo</groupId>
<artifactId>springMongoDBDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springMongoDBDemo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.example.demo.springMongoDBDemo;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
//Creating MongoTemplate Java based
@Configuration
public class MongoConfig {
@Bean
MongoClient mongoClient() {
return MongoClients.create("mongodb://localhost:27017");
}
@Bean
MongoTemplate mongoTemplate(MongoClient mongoClient) {
return new MongoTemplate(mongoClient, "tutorials");
}
}
package com.example.demo.springMongoDBDemo.Service;
import com.example.demo.springMongoDBDemo.model.Tutorials;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class CustomMongoTemplate {
@Autowired
MongoTemplate mongoTemplate;
public Tutorials save(Tutorials tutorials) {
return mongoTemplate.save(tutorials);
}
public long update(Tutorials tutorials, String title) {
Query query = new Query();
query.addCriteria(Criteria.where("title").is(title));
Update update = new Update();
update.set("description", tutorials.getDescription());
update.set("published", true);
UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Tutorials.class);
if (updateResult == null) {
return 0;
} else {
return updateResult.getModifiedCount();
}
}
public List<Tutorials> getByTitle(String title) {
Query query = new Query();
query.addCriteria(Criteria.where("title").in(title)).fields().include("title").include("description");
return mongoTemplate.find(query, Tutorials.class);
}
public List<Tutorials> getAll() {
return mongoTemplate.findAll(Tutorials.class);
}
public Tutorials deleteByTitle(String title) {
Query query = new Query();
query.addCriteria(Criteria.where("title").is(title));
return mongoTemplate.findAndRemove(query, Tutorials.class);
}
public UpdateResult upsertByTitle(String title, String description) {
Query query = new Query(Criteria.where("title").is(title).and("description").is(description));
Update update = new Update();
update.set("title", "Ravinder");
return mongoTemplate.update(Tutorials.class).matching(query).apply(update).upsert();
}
public Tutorials findAndModify(String title, String description) {
Query query = new Query(Criteria.where("title").is(title));
Update update = new Update();
update.set("description", description);
return mongoTemplate.update(Tutorials.class).matching(query).apply(update)
.withOptions(FindAndModifyOptions.options().returnNew(true))
.findAndModifyValue();
}
}
package com.example.demo.springMongoDBDemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringMongoDbDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringMongoDbDemoApplication.class, args);
}
}
package com.example.demo.springMongoDBDemo.controller;
import com.example.demo.springMongoDBDemo.Service.CustomMongoTemplate;
import com.example.demo.springMongoDBDemo.model.Tutorials;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/mongo")
public class CustomMongoTemplateController {
@Autowired
private CustomMongoTemplate customMongoTemplate;
@PostMapping("/save")
public ResponseEntity<Tutorials> saveTutorials(@RequestBody Tutorials tutorials) {
try {
Tutorials tutorials1 = customMongoTemplate.save(tutorials);
return new ResponseEntity<>(tutorials1, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PostMapping("/update")
public ResponseEntity<Long> Update(@RequestBody Tutorials tutorials, @PathVariable("title") String title) {
try {
long update = customMongoTemplate.update(tutorials, title);
return new ResponseEntity<>(update, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/upsertByTitle")
public ResponseEntity<Long> upsertByTitle(@RequestParam String title, @RequestParam String description) {
UpdateResult updateResult = customMongoTemplate.upsertByTitle(title, description);
if (updateResult == null) {
return new ResponseEntity<>(0L, HttpStatus.NO_CONTENT);
} else {
return new ResponseEntity<>(updateResult.getModifiedCount(), HttpStatus.OK);
}
}
@GetMapping("/findAndModif")
public ResponseEntity<Tutorials> findAndModif(@RequestParam String title, @RequestParam String description){
ResponseEntity<Tutorials> tutorialsResponseEntity = new ResponseEntity<>(customMongoTemplate.findAndModify(title, description), HttpStatus.OK);
return tutorialsResponseEntity;
}
}
package com.example.demo.springMongoDBDemo.controller;
import com.example.demo.springMongoDBDemo.model.Tutorials;
import com.example.demo.springMongoDBDemo.repository.CustomQueryRepository;
import com.example.demo.springMongoDBDemo.repository.TutorialsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/tutorials")
public class TutorialsController {
@Autowired
private TutorialsRepository tutorialsRepository;
@Autowired
private CustomQueryRepository customQueryRepository;
@PostMapping("/save")
public ResponseEntity<Tutorials> saveTutorials(@RequestBody Tutorials tutorials) {
try {
Tutorials tutorials1 = tutorialsRepository.insert(tutorials);
return new ResponseEntity<>(tutorials1, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/getAll")
public ResponseEntity<List<Tutorials>> getAllTutorials() {
List<Tutorials> getAllTutorials = tutorialsRepository.findAll();
return new ResponseEntity<>(getAllTutorials, HttpStatus.OK);
}
@GetMapping(value = "/getById/{id}")
public ResponseEntity<Tutorials> getById(@PathVariable("id") String id) {
Optional<Tutorials> getById = tutorialsRepository.findById(id);
if (getById.isPresent()) {
return new ResponseEntity<>(getById.get(), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@DeleteMapping("/delete/{id}")
public void delete(@PathVariable("id") String id) {
try {
Optional<Tutorials> tutorial = tutorialsRepository.findById(id);
Tutorials tutorials = tutorial.isPresent() ? tutorial.get() : null;
if (tutorials != null) {
tutorialsRepository.delete(tutorials);
}
} catch (Exception e) {
}
}
@PutMapping("/update/{id}")
public ResponseEntity<Tutorials> update(@PathVariable("id") String id, @RequestBody Tutorials updateTutorials) {
Optional<Tutorials> tutorial = tutorialsRepository.findById(id);
if (tutorial.isPresent()) {
Tutorials tutorials = tutorial.get();
updateTutorials.setId(tutorials.getId());
updateTutorials.setTitle(tutorials.getTitle());
updateTutorials.setDescription(tutorials.getDescription());
return new ResponseEntity<>(tutorialsRepository.save(updateTutorials), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@GetMapping(value = "/getByTitle/{title}")
public ResponseEntity<Tutorials> getByTitle(@PathVariable("title") String title) {
Tutorials byTitle = customQueryRepository.getByTitle(title);
if (byTitle != null) {
return new ResponseEntity<>(byTitle, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@GetMapping(value = "/getByTitleAndDesc")
public ResponseEntity<Tutorials> getByTitleAndDescription(@RequestParam String title, @RequestParam String description) {
Tutorials byTitle = customQueryRepository.getByTileAndDescription(title, description);
if (byTitle != null) {
return new ResponseEntity<>(byTitle, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@GetMapping(value = "/getByTitleOrDesc")
public ResponseEntity<List<Tutorials>> getByTitleOrDescription(@RequestParam String title, @RequestParam String description) {
List<Tutorials> byTitleOrDescription = customQueryRepository.getByTitleOrDescription(title, description);
if (byTitleOrDescription != null) {
return new ResponseEntity<>(byTitleOrDescription, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@GetMapping(value = "/getByQuery")
public ResponseEntity<List<Tutorials>> getByQuery() {
List<Tutorials> byTitleOrDescription = customQueryRepository.getByQuery();
if (byTitleOrDescription != null) {
return new ResponseEntity<>(byTitleOrDescription, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
package com.example.demo.springMongoDBDemo.model;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
@Data
@Getter
@Setter
@ToString
public class Tutorials {
@Id
private String id;
private String title;
private String description;
private boolean published;
}
package com.example.demo.springMongoDBDemo.repository;
import com.example.demo.springMongoDBDemo.model.Tutorials;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CustomQueryRepository extends MongoRepository<Tutorials, String> {
@Query("{title: ?0}")
public Tutorials getByTitle(String title);
//Named Parameter
@Query("{'title': :#{#title}, 'description': :#{#description}}")
public Tutorials getByTileAndDescription(@Param("title") String title, @Param("description") String description);
@Query("{$or :[{title: ?0},{description: ?1}]}")
public List<Tutorials> getByTitleOrDescription(String title, String description);
@Query(value = "{}", fields = "{title:1,description:1}")
List<Tutorials> getByQuery();
}
package com.example.demo.springMongoDBDemo.repository;
import com.example.demo.springMongoDBDemo.model.Tutorials;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TutorialsRepository extends MongoRepository<Tutorials,String> {
}
spring.data.mongodb.uri=mongodb://localhost:27017/
spring.data.mongodb.database=tutorials
\ No newline at end of file
package com.example.demo.springMongoDBDemo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringMongoDbDemoApplicationTests {
@Test
void contextLoads() {
}
}
spring.data.mongodb.uri=mongodb://localhost:27017/
spring.data.mongodb.database=tutorials
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment