validation

parent 1f01c497
server.port = 8082
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.ddl-auto=none
spring.jpa.defer-datasource-initialization=true
spring.sql.init.mode=always
spring.datasource.url=jdbc:mysql://localhost:3306/school
......
......@@ -41,6 +41,16 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.2.3.Final</version>
</dependency>
</dependencies>
<build>
......
package com.example.teacher.controller;
import com.example.teacher.custom_exception.TeacherNotFoundException;
import com.example.teacher.model.Teacher;
import com.example.teacher.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
......@@ -20,14 +23,15 @@ public class TeacherController {
// POST methods
@PostMapping
public ResponseEntity<Teacher> createTeacher(@RequestBody Teacher teacher) {
Teacher myStudent = teacherService.createAndUpdateTeacher(teacher);
return new ResponseEntity<Teacher>(myStudent, HttpStatus.CREATED);
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<Teacher> createTeacher(@Valid @RequestBody Teacher teacher) {
Teacher myTeacher = teacherService.createAndUpdateTeacher(teacher);
return new ResponseEntity<Teacher>(myTeacher, HttpStatus.CREATED);
}
// GET methods
@GetMapping("/{id}")
public ResponseEntity<Optional<Teacher>> findTeacherById(@PathVariable int id) {
public ResponseEntity<Optional<Teacher>> findTeacherById(@PathVariable int id) throws TeacherNotFoundException {
Optional<Teacher> myTeacher = teacherService.findTeacherById(id);
if (myTeacher.isPresent()) {
return new ResponseEntity<Optional<Teacher>>(myTeacher, HttpStatus.FOUND);
......
package com.example.teacher.custom_exception;
public class TeacherNotFoundException extends Exception{
public TeacherNotFoundException(String message){
super(message);
}
}
package com.example.teacher.exception_advice;
import com.example.teacher.custom_exception.TeacherNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class MyExceptionHandlerAdvice{
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Map<String, String> handleArgumentNotValidException(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(x -> {
errors.put(x.getField(), x.getDefaultMessage());
});
return errors;
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(TeacherNotFoundException.class)
public String handleTeacherNotFoundException(TeacherNotFoundException ex) {
return ex.getMessage();
}
}
......@@ -6,6 +6,7 @@ import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.util.Date;
@Entity
......@@ -16,8 +17,12 @@ public class Teacher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@NotBlank(message = "teacher name should not be blank or null")
private String name;
@Min(value = 24, message = "age should not be less than 24")
@Max(value = 65, message = "age should not be greater than 65")
private int age;
@NotBlank(message = "teacher subject should not be blank or null")
private String subject;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd:MM:yyyy")
@Temporal(TemporalType.DATE)
......
package com.example.teacher.service;
import com.example.teacher.custom_exception.TeacherNotFoundException;
import com.example.teacher.model.Teacher;
import com.example.teacher.repository.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -29,10 +30,11 @@ public class TeacherService {
.collect(Collectors.toList());
}
public Optional<Teacher> findTeacherById(int id) {
return teacherRepository
public Optional<Teacher> findTeacherById(int id) throws TeacherNotFoundException {
return Optional.ofNullable(teacherRepository
.findById(id)
.filter(Teacher::isActive);
.filter(Teacher::isActive)
.orElseThrow(() -> new TeacherNotFoundException("teacher with id"+ id + " found")));
}
public Optional<Teacher> findTeacherByName(String name) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment