Spring Boot 完整 REST CRUD 示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28228068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:20:06  来源:igfitidea点击:

Spring Boot full REST CRUD example

springspring-boot

提问by Jose Leon

Does anyone have a full spring boot REST CRUD example? The spring.io site just has a RequestMapping for GET. I'm able to get POST and DELETE working but not PUT.

有人有完整的 Spring Boot REST CRUD 示例吗?spring.io 站点只有一个用于 GET 的 RequestMapping。我能够使 POST 和 DELETE 工作但不能 PUT。

I suspect it's how I'm trying to get the params where the disconnect is, but I have not seen an example where someone is performing an update.

我怀疑这就是我试图获取断开连接的参数的方式,但我还没有看到有人执行更新的示例。

I'm currently using the SO iPhone app so I can't paste my current code. Any working examples would be great!

我目前正在使用 SO iPhone 应用程序,因此无法粘贴我当前的代码。任何工作示例都会很棒!

回答by Eddú Meléndez

As you can see I have implemented two way to update. The first one will receive a json, and the second one will receive the cusotmerId in the URL and json also.

如您所见,我已经实现了两种更新方式。第一个将接收一个 json,第二个将在 URL 和 json 中接收 cusotmerId。

@RestController
@RequestMapping("/customer")
public class CustomerController {


    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Customer greetings(@PathVariable("id") Long id) {
        Customer customer = new Customer();
        customer.setName("Eddu");
        customer.setLastname("Melendez");
        return customer;
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<Customer> list() {
        return Collections.emptyList();
    }

    @RequestMapping(method = RequestMethod.POST)
    public void add(@RequestBody Customer customer) {

    }

    @RequestMapping(method = RequestMethod.PUT)
    public void update(@RequestBody Customer customer) {

    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public void updateById(@PathVariable("id") Long id, @RequestBody Customer customer) {

    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void delete() {

    }

    class Customer implements Serializable {

        private String name;

        private String lastname;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public void setLastname(String lastname) {
            this.lastname = lastname;
        }

        public String getLastname() {
            return lastname;
        }
    }
}

回答by user3198621

Or, alternatively:

或者,或者:

@RepositoryRestResource
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}

To use the annotation org.springframework.data.rest.core.annotation.RepositoryRestResource, you need to add the following dependency to your pom.xml:

要使用 annotation org.springframework.data.rest.core.annotation.RepositoryRestResource,您需要将以下依赖项添加到 pom.xml 中:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>

回答by David Pham

An alternative update returns ResponseEntity object.

另一种更新返回 ResponseEntity 对象。

@RestController
@RequestMapping("/fruits")
public class FruitController {

    private final Logger LOG = LoggerFactory.getLogger(FruitController.class);

    @Autowired
    private FruitService fruitService;

    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<List<Fruit>> getAll(@RequestParam(value = "offset", defaultValue = "0") int index,
            @RequestParam(value = "numberOfRecord", defaultValue = "10") int numberOfRecord) {
        LOG.info("Getting all fruits with index: {}, and count: {}", index, numberOfRecord);
        List<Fruit> fruits = fruitService.getAll(index, numberOfRecord);

        if (fruits == null || fruits.isEmpty()) {
            return new ResponseEntity<List<Fruit>>(HttpStatus.NO_CONTENT);
        }

        return new ResponseEntity<List<Fruit>>(fruits, HttpStatus.OK);
    }

    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public ResponseEntity<Fruit> get(@PathVariable("id") int id) {
        LOG.info("Getting fruit with id: {}", id);
        Fruit fruit = fruitService.findById(id);

        if (fruit == null) {
            return new ResponseEntity<Fruit>(HttpStatus.NOT_FOUND);
        }

        return new ResponseEntity<Fruit>(fruit, HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<Void> create(@RequestBody Fruit fruit, UriComponentsBuilder ucBuilder) {
        LOG.info("Creating fruit: {}", fruit);

        if (fruitService.exists(fruit)) {
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }

        fruitService.create(fruit);

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/fruit/{id}").buildAndExpand(fruit.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }

    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    public ResponseEntity<Fruit> update(@PathVariable int id, @RequestBody Fruit fruit) {
        LOG.info("Updating fruit: {}", fruit);
        Fruit currentFruit = fruitService.findById(id);

        if (currentFruit == null) {
            return new ResponseEntity<Fruit>(HttpStatus.NOT_FOUND);
        }

        currentFruit.setId(fruit.getId());
        currentFruit.setName(fruit.getName());

        fruitService.update(fruit);
        return new ResponseEntity<Fruit>(currentFruit, HttpStatus.OK);
    }

    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Void> delete(@PathVariable("id") int id) {
        LOG.info("Deleting fruit with id: {}", id);
        Fruit fruit = fruitService.findById(id);

        if (fruit == null) {
            return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
        }

        fruitService.delete(id);
        return new ResponseEntity<Void>(HttpStatus.OK);
    }
}

From Spring MVC RESTFul Web Service CRUD Example

来自Spring MVC RESTFul Web 服务 CRUD 示例

回答by Sagar Jadhav

I have prepared a set of tutorials on Spring Boot CRUD Operations. Following are the content of tutorials:

我准备了一套关于 Spring Boot CRUD 操作的教程。以下是教程内容:

  1. How to create Spring Boot Project using Spring Tool Suite
  2. How to implement GET & POST method in spring boot restful web service
  3. How to implement PUT & DELETE method in spring boot restful web service
  4. Integrate PostgreSQL database using spring boot JPA with spring boot restful web service
  5. Use of CURL commands
  1. 如何使用 Spring Tool Suite 创建 Spring Boot 项目
  2. Spring Boot Restful web service中如何实现GET&POST方法
  3. 如何在spring boot restful web service中实现PUT&DELETE方法
  4. 使用 spring boot JPA 将 PostgreSQL 数据库与 spring boot restful web 服务集成
  5. CURL 命令的使用

Youtube Tutorials:

优酷教程:

  1. Spring Boot Restful Web Service Tutorial | Tutorial 1 - Introduction
  2. Spring Boot Restful Web Services CRUD Example GET & POST | Tutorial - 2
  3. Spring boot CRUD Operations example PUT & DELETE | Tutorial - 3
  4. Spring Boot JPA | In 5 Simple Steps Integrate PostgreSQL Database | Tuorial - 4
  1. Spring Boot Restful Web 服务教程 | 教程 1 - 介绍
  2. Spring Boot Restful Web 服务 CRUD 示例 GET & POST | 教程 - 2
  3. Spring Boot CRUD 操作示例 PUT & DELETE | 教程 - 3
  4. Spring Boot JPA | 只需 5 个简单步骤即可集成 PostgreSQL 数据库 | 教程 - 4

Visit Blogfor more details.

访问博客了解更多详情。

回答by John Detroit

You can find complete project on Spring Boot REST API with CRUD here:

您可以在此处使用 CRUD 找到有关 Spring Boot REST API 的完整项目:

Spring Boot full REST CRUD example

Spring Boot 完整 REST CRUD 示例

回答by Sumit

package com.controllers;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.cats.hcm.bussinessObjects.Address;
import com.cats.hcm.bussinessObjects.Employee;
import com.cats.hcm.bussinessObjects.EmployeeBO;
import com.cats.hcm.bussinessObjects.MaritalStatus;
import com.cats.hcm.bussinessObjects.State;
import com.cats.hcm.repository.EmployeeRepositoryImpl;
import com.cats.hcm.repository.MaritalStatusRepositoryImpl;
import com.cats.hcm.repository.Repository;
import com.cats.hcm.repository.StateRepositoryImpl;
import com.cats.hcm.services.EmployeeServiceImpl;
import com.google.gson.Gson;

@Controller
@RequestMapping("/newemployee")
public class NewEmployeeController {

    private static final Logger logger = LoggerFactory.getLogger(Repository.class);

    @Autowired
    Repository repository;

    @Autowired
    StateRepositoryImpl stateRepositoryImpl;

    @Autowired
    MaritalStatusRepositoryImpl maritalStatusRepositoryImpl;

    @Autowired
    EmployeeRepositoryImpl employeeRepositoryImpl;

    @Autowired
    EmployeeServiceImpl employeeServiceImpl;


    @RequestMapping(value="/save", method=RequestMethod.POST)
    public @ResponseBody String addEmployee(@RequestBody EmployeeBO employeeBO, BindingResult bindingResult) throws SecurityException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, IOException {

        logger.info("==========="+new Gson().toJson(employeeBO));
        logger.info("========Employee ID========"+employeeBO.getEmployeeId());
        repository.addToDataBase(employeeBO);   
        String msg="Success";
        return msg;
    }


    @RequestMapping(value="/update", method=RequestMethod.POST)
    public @ResponseBody String updateEmployee(@RequestBody EmployeeBO employeeBO, BindingResult bindingResult) throws SecurityException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, IOException {

        logger.info("==========="+new Gson().toJson(employeeBO));
        logger.info("========Employee ID========"+employeeBO.getEmployeeId());

        //Deleting Existing Employee
        Boolean isDeleted = employeeServiceImpl.deleteEmployeeDetails(employeeBO.getEmployeeId());
        if(isDeleted) {
            repository.addToDataBase(employeeBO);
        }
        String msg="Success";
        return msg;
    }

    @RequestMapping("/employeeData")
    public @ResponseBody List<Employee> getEmployeeDataTablePage() {
        logger.info("======getEmployeeDataTablePage======");
        List<Employee> employeeList = employeeRepositoryImpl.readAll(); 
        logger.info("========EmployeeList========="+new Gson().toJson(employeeList));

        return employeeList;        
    }


    @RequestMapping("/modifyPage")
    public @ResponseBody List<Employee> getEmployeeModifyPage(@RequestParam("employeeId") String employeeId) {
        logger.info("========getEmployeeModifyPage====EmployeeID:===="+employeeId);
        //List<State> stateList = stateRepositoryImpl.readAll();
        //List<MaritalStatus> maritalStatusList = maritalStatusRepositoryImpl.readAll();

        //model.addAttribute("stateList", stateList);
        //model.addAttribute("maritalStatusList", maritalStatusList);

        List<Employee> employeeList = employeeRepositoryImpl.readAll();
        logger.info("========employeeList:===="+employeeList);


        EmployeeBO employeeBO = employeeServiceImpl.getEmployeeBO(employeeId);
        logger.info("========getEmployeeModifyPage====EmployeeBO:===="+employeeBO);


        return employeeList;

        //return new ModelAndView("apps-mod-employee", "employee", employeeBO);
    }

    @RequestMapping("/delete")
    public @ResponseBody String deleteEmployee(@RequestParam("employeeId") String employeeId) {
        logger.info("========deleteEmployee===EmployeeID:===="+employeeId);
        //employeeRepositoryImpl.delete(employeeServiceImpl.getEmployeeBO(employeeId));
        Boolean isDeleted = employeeServiceImpl.deleteEmployeeDetails(employeeId);
        if(isDeleted) {
            logger.info("========Employee Record Deleted===EmployeeID:===="+employeeId);
        }
        return "redirect:/employee/employeeDataTable";
    }
    /*@RequestMapping("/employeeDataByEmpId")
     public String getEmployeeAddPage(Map<String, Object> model) { 
    public ModelAndView getEmployeeDataByEmpId(ModelMap model,HttpServletRequest request, HttpServletResponse response) {
        logger.info("======getEmployeeDataByEmpId======");

        String EmployeeID=request.getParameter("empId");

        Employee employee = employeeRepositoryImpl.read(EmployeeID);

        logger.info("========Employee========="+new Gson().toJson(employee));

        model.addAttribute(new EmployeeBO());
        model.addAttribute("employeeByEmpId", employee);
        //return "apps-add-employee";
        //return new ModelAndView("apps-add-employee");
        return new ModelAndView("apps-employee", "employee", new EmployeeBO());
    }*/
}

回答by Anand

You can get my full RESTful server and client app using SpringBoot at Spring RESTFul Examples at github

您可以在 github 的 Spring RESTFul 示例中使用 SpringBoot 获取我的完整 RESTful 服务器和客户端应用程序