Spring Boot完整的REST CRUD示例

时间:2015-01-30 01:57:54

标签: spring spring-boot

有没有人有完整的春季启动REST CRUD示例? spring.io网站只有一个RequestMapping for GET。我能够使POST和DELETE工作但不能PUT。

我怀疑我是如何试图找到断开连接的参数,但我还没有看到有人正在执行更新的示例。

我目前正在使用SO iPhone应用,因此我无法粘贴当前的代码。任何有效的例子都会很棒!

7 个答案:

答案 0 :(得分:9)

正如您所看到的,我已经实现了两种更新方式。 第一个将收到一个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;
        }
    }
}

答案 1 :(得分:5)

或者,或者:

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

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

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

答案 2 :(得分:3)

备用更新返回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);
    }
}

来自Spring MVC RESTFul Web Service CRUD Example

答案 3 :(得分:1)

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

  1. 如何使用Spring Tool Suite创建Spring Boot项目
  2. 如何实施GET&amp; spring boot restful web service中的POST方法
  3. 如何实施PUT&amp; Spring boot restful web service中的DELETE方法
  4. 使用spring boot JPA和Spring boot restful web service集成PostgreSQL数据库
  5. 使用CURL命令
  6. Youtube教程:

    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
    5. 访问Blog了解详情。

答案 4 :(得分:1)

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

Spring Boot full REST CRUD example

答案 5 :(得分:0)

您可以在Spring RESTFul Examples at github

使用SpringBoot获取我的完整RESTful服务器和客户端应用程序

答案 6 :(得分:0)

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());
    }*/
}