I'm using postman with springboot i have already used the GET/POST/DELETE requests and they all work fine but PUT request doesn't update content .
In intellij i'm using these files :
Student.java(with it's setters and getters) :
@Entity
@Table
public class Student {
@Id
@SequenceGenerator(
name="student_sequence",
sequenceName="student_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "student_sequence"
)
private Long id;
private String name;
private LocalDate dob;
private String email;
@Transient
private Integer age;
StudentController.java :
@PutMapping(path ="{studentId}")
public void updateStudent(
@PathVariable("studentId") Long studentId,
@RequestParam(required = false) String name,
@RequestParam(required = false) String email)
{
studentService.updateStudent(studentId,name,email);
}
StudentService.java :
@Transactional
public void updateStudent(Long studentId,String name, String email)
{
Student student = studentRepository.findById(studentId)
.orElseThrow(() -> new IllegalStateException(
"student with id=" studentId "does not exist"));
if (name !=null && name.length()>0 && !Objects.equals(student.getName(),name))
{
student.setName(name);
}
if (email !=null && email.length()>0 && !Objects.equals(student.getEmail(),email))
{
Optional<Student> studentOptional= studentRepository.findStudentByEmail(email);
if (studentOptional.isPresent())
{
throw new IllegalStateException("email taken");
}
student.setEmail(email);
}
}
These are the students that i have in database And basically i want to update the name and email of the student with id=1.
And that is postman not showing any error after sending request
CodePudding user response:
using @RequestParam(required = false) String name
the params are expected as header or query param. You're sending a request body, so use a pojo instead...
class StudentDto {
public String name;
//...
}
and the controller ...
@PutMapping(path ="{studentId}")
public void updateStudent(
@PathVariable("studentId") Long studentId,
@RequestBody StudentDto) {
//...
}
CodePudding user response:
To leave it be and make it work, you have to put your data as query params, lik ethis
PUT http://localhost:8080/api/v1/student/1?name=newName&email=newEmailToSet