Restful: Spring Boot with Mongodb

Why is mongodb?

Continuing with the previous dailyReport project, today's task is to select mongogdb as persistent storage.

Contrasting nosql and rdbms and choice, I refer to a lot of information, the key point is: nosql can easily expand the list, for the rapidly changing business scenario is very suitable; rdbms you need to install the relational database model to be built in business mode, the scene is ripe for business systems. My current project --dailyReport, I do not determine that for a report, which should have its attributes: date, title, content, address, images, etc., based on this I chose this project as a persistent mongodb storage.

How mongodb used in conjunction with the spring boot

  • Pom modify files, increase support mongodb

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>
  • Report redesign entity class, id attribute is used to mongodb, modified with annotations @Id; overloaded toString function using String.format outputs the object.

import org.springframework.data.annotation.Id;/**
 * @author duqi
 * @create 2015-11-17 19:31
 */public class Report {    @Id
    private String id;    private String date;    private String content;    private String title;    public Report() {

    }    public Report(String date, String title, String content) {        this.date = date;        this.title = title;        this.content = content;
    }    public String getId() {        return id;
    }    public void setId(String id) {        this.id = id;
    }    public String getTitle() {        return title;
    }    public void setTitle(String title) {        this.title = title;
    }    public String getDate() {        return date;
    }    public void setDate(String dateStr) {        this.date = dateStr;
    }    public String getContent() {        return content;
    }    public void setContent(String content) {        this.content = content;
    }    @Override
    public String toString() {        return String.format("Report[id=%s, date='%s', content='%s', title='%s']", id, date, content, title);
    }
}
  • Increase ReportRepository interface that inherits from MongoRepository the interface, the interface comprising a common MongoRepository CRUD operations, for example: save, insert, findall like. We can define your own interface to find, for example, according to the title search report, specific ReportRepository interface code as follows:

import org.springframework.data.mongodb.repository.MongoRepository;import java.util.List;/**
 * Created by duqi on 15/11/22.
 */public interface ReportRepository extends MongoRepository<Report, String> {    Report findByTitle(String title);    List<Report> findByDate(String date);
}
  • ReportService modify the code, increase createReport function, which according to Map initialization parameters Conroller came a Report object and call ReportRepository to save the data in mongodb; for getReportDetails function, still open the cache, if no cache when the query interface to use findByTitle mongodb database.

import com.javadu.dailyReport.domain.Report;import com.javadu.dailyReport.domain.ReportRepository;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cache.annotation.Cacheable;import org.springframework.stereotype.Service;import java.util.Map;/**
 * @author duqi
 * @create 2015-11-17 20:05
 */@Servicepublic class ReportService {    @Autowired
    private ReportRepository repository;    public Report createReport(Map<String, Object> reportMap) {
        Report report = new Report(reportMap.get("date").toString(),
                reportMap.get("title").toString(),
                reportMap.get("content").toString());

        repository.save(report);        return report;
    @Cacheable} (value = "reportcache", keyGenerator = "wiselyKeyGenerator") public Report getReportDetails (String title) { 
        System.out.println ( "no-cache when the call here --- database queries, title =" + title); repository.findByTitle return (title); 
    } 
}

Restful Interface

Controller is responsible only for the specific URL mapping Service, and conduct real business logic in the Service layer, business logic here very simple, so it is Service layer is optional, but if the business logic complicated (for example through RPC calling a remote service), these operations need to complete the service layer. Overall, Controller layer is only responsible for: + construction Response to forward the request data; when necessary permissions to verify, it is also using the Controller layer aop completed.

For all the general operations Report (an entity) is placed in a Controller, and notes modified with @RestController and @RequestMapping ( "/ report"), represents all xxxx / report URL will be processed by the ReportController.

. POST

Report operation for increasing, we choose the POST method, and the request using the POST request body @RequestBody, i.e. function parameters createReport modification;

. GET

For inquiry report operation, we choose the GET method, the form of the URL is: "xxx / report / $ {report's title}", using the modified parameter @PathVariable url input, that title.

import com.javadu.dailyReport.domain.Report;import com.javadu.dailyReport.service.ReportService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import java.util.LinkedHashMap;import java.util.Map;/**
 * @author duqi
 * @create 2015-11-17 20:10
 */@RestController@RequestMapping("/report")public class ReportController {    private static final Logger logger = LoggerFactory.getLogger(ReportController.class);    @Autowired
    ReportService reportService;    @RequestMapping(method = RequestMethod.POST)    public Map<String, Object> createReport(@RequestBody Map<String, Object> reportMap) {
        logger.info("createReport");
        Report report = reportService.createReport(reportMap);

        Map<String, Object> response = new LinkedHashMap<String, Object>();
        response.put("message", "Report created successfully");
        response.put("report", report);        return response;
    }    @RequestMapping(method = RequestMethod.GET, value = "/{reportTitle}")    public Report getReportDetails(@PathVariable("reportTitle") String title) {
        logger.info("getReportDetails");        return reportService.getReportDetails(title);
    }
}

Update and delete operations me here is not about the

Guess you like

Origin blog.51cto.com/14028890/2416796