Я только что получил Spring Framework и передаю базовые c шаги, однако я получил ошибку, которая не произошла. Я просто использую Почтальон для связи с данными. Функции Get и Delete были гладкими, однако Post и Put - нет. Это мой код:
Класс EmployeeRepo
package com.employee.demo.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.employee.demo.model.Employee;
public interface EmployeeRepo extends JpaRepository<Employee, Integer>{
}
Класс Сотрудник
package com.employee.demo.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Employee {
@Id
private int id;
private String name;
private double salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String toString() {
return "Employee with [ID: " + id + ", name: " + name + " and salary: " + salary + "]";
}
}
Класс EmployeeController
package com.employee.demo.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.employee.demo.dao.EmployeeRepo;
import com.employee.demo.model.Employee;
@RestController
public class EmployeeController {
@Autowired
EmployeeRepo repo;
@RequestMapping("/")
public String home() {
return "home.jsp";
}
@DeleteMapping("/employee/{id}")
public String deleteEmployee(@PathVariable int id) {
Employee empl = repo.getOne(id);
repo.delete(empl);
return "deleted";
}
@PostMapping("/employee")
public Employee addEmployee(Employee empl) {
repo.save(empl);
return empl;
}
@GetMapping(path = "/employees")
public List<Employee> getEmployees() {
return repo.findAll();
}
@PutMapping(path = "/employee", consumes = {"application/json"})
public Employee saveOrUpdateEmployee(@RequestBody Employee empl) {
repo.save(empl);
return empl;
}
@RequestMapping("/employee/{id}")
public Optional<Employee> getEmployee(@PathVariable int id) {
return repo.findById(id);
}
}
И это то, что я получил от почтальона для почтового запроса