CRUD Operation Using Spring Boot
CRUD Operation Using Spring Boot
Pragyanand Singh
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
Table of Contents
1. CRUD Operation using spring boot .......................................................................................................................................................................................... 2
1) Employee class ..................................................................................................................................................................................................................... 2
2) Repository ............................................................................................................................................................................................................................ 3
3) Controller Class 1 for view ................................................................................................................................................................................................... 4
4) Controller Class 2 for postman ............................................................................................................................................................................................ 7
5) Rest Controller Advice's ....................................................................................................................................................................................................... 9
6) User defined Runtime Exception ....................................................................................................................................................................................... 10
7) Main class........................................................................................................................................................................................................................... 11
8) Page for Add Employee details .......................................................................................................................................................................................... 14
9) Home page to view all employee details ........................................................................................................................................................................... 12
10) Page for update Employee’s details............................................................................................................................................................................... 15
P a g e 1 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
Other Annotation:
• @DateTimeFormat(pattern = "yyyy-MM-dd")
• @Positive and @PositiveOrZero apply to numeric values and validate that they are strictly positive, or positive including 0.
• @Negative and @NegativeOrZero apply to numeric values and validate that they are strictly negative, or negative including 0.
• @Past and @PastOrPresent validate that a date value is in the past or the past including the present; can be applied to date types including those
added in Java 8.
• @Future and @FutureOrPresent validate that a date value is in the future, or in the future including the present.
P a g e 2 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
2) Repository
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
P a g e 3 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
@GetMapping("/add")
public String redirecttoAdd(Model m) {
Employee e = new Employee();
m.addAttribute("emp", e);
return "add";
}
P a g e 4 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
@PostMapping("/save")
public String save(@Valid @ModelAttribute("emp") Employee e, BindingResult result) { Commented [PS10]: @Valid annotation will tell spring
if (result.hasErrors()) { to go and validate the data passed into the controller
@GetMapping("/update")
public String update(@RequestParam String id, Model m) { Commented [PS13]: @RequestParam is used to
int i = Integer.parseInt(id); capture query parameters or form parameters from the
Employee e = repo.findById(i).get(); URL, whereas @PathVariable is used to capture values
m.addAttribute("emp", e); from the URL path
return "update";
}
@GetMapping("/{id}")
public String updateEmp(@PathVariable int id, Model m) { Commented [PS14]: @PathVariable annotation is
Employee e = repo.findById(id).get(); used to extract the value from the URI.
m.addAttribute("Emp", e);
return "index";
}
P a g e 5 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
@PostMapping("/updateEmp")
public String updateEmp(@RequestParam String id, @RequestParam String name, @RequestParam String mob,
@RequestParam String salary) {
Employee e = new Employee();
e.setId(Integer.parseInt(id));
e.setName(name);
e.setMob(Long.parseLong(mob));
e.setSalary(Double.parseDouble(salary));
repo.save(e);
return "redirect:/employee"; Commented [PS15]: redirect: prefix Spring provides
} another option to perform redirection,
P a g e 6 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
@GetMapping("/{id}")
public ResponseEntity<Employee> getById(@PathVariable Integer id) { Commented [PS16]: ResponseEntity represents the
Optional<Employee> o = repo.findById(id); whole HTTP response: status code, headers, and body.
if (o.isPresent()) { As a result, we can use it to fully configure the HTTP
return ResponseEntity.ok().header("head", "Employee details").body(o.get()); response.
// return new ResponseEntity<>(o.get(),HttpStatus.OK);
} else
return ResponseEntity.status(HttpStatus.NOT_FOUND).header("head", "No Employee").build();
}
@GetMapping("/name")
public String headerData(@RequestHeader String name) { Commented [PS17]: @RequestHeader annotation used to
System.out.println(name); bind a request header to a method argument in a controller.
return name;
}
@GetMapping
public String createSession(HttpSession session) { // create session
session.setAttribute("emp", "mohan");
return "mohan is added to session";
}
@GetMapping("find/{name}")
public String findNo(@PathVariable String name) {
long mob = repo.noByName(name); Commented [PS18]: Custom method created in
repository
return name + ": " + mob;
}
P a g e 7 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
@GetMapping("/session")
public String getSession(@SessionAttribute String emp) { // get session attribute Commented [PS19]: @SessionAttributes is used to bind
session attributes or values in the HTTP Servlet session to a
return emp; controller method parameter
}
}
P a g e 8 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NullPointerException.class) Commented [PS22]: @ExceptionHandler is an
public Map<String, String> noEmployee(NullPointerException ex) { annotation used to handle the specific exceptions and
Map<String, String> map = new HashMap<>(); sending the custom responses to the client.
map.put("status", HttpStatus.NOT_FOUND.toString());
map.put("error", ex.getMessage());
return map;
}
}
P a g e 9 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
public NoNameFoundException() {
super("Employee not exist");
}
}
P a g e 10 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
7) Main class
System.out.println("done");
}
P a g e 11 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
P a g e 12 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
<tbody>
<tr th:each="myEmp : ${Emp}"> Commented [PS26]: Th:each is an attribute used to
<td th:text="${myEmp.id}"></td> iterate over collections (lists, sets, arrays, etc.)
<td th:text="${myEmp.name}"></td>
<td th:text="${myEmp.mob}"></td> Commented [PS27]: ${Emp} where Emp is a collection
<td th:text="${myEmp.salary}"></td> object
<td> Commented [PS28]: variable expressions (${...}) The
<a class="btn btn-primary" th:href="@{employee/update(id=${myEmp.id})}" role="button">Update</a>
expression inside the curly braces represents the name
<a class="btn btn-danger" th:href="@{employee/delete(id=${myEmp.id})}" role="button">Delete</a>
of the variable in the model.
</td>
Commented [PS29]: Th:text attribute will replace the
</tr> inner text of the HTML element with the value of the
</tbody> expression.
</table>
Commented [PS30]: Th:href It allows you to create
<div class="text-center">
hyperlinks (anchors) with dynamic URLs based on values
<a class="btn btn-success" href="employee/add" role="button" style="width: 200px;">Add</a>
from your model or Thymeleaf context.
</div>
</div>
</body>
</html>
P a g e 13 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
<label for="name" >mob</label> Commented [PS32]: th:field is used with *{name} to bind
<input type="text" th:field="*{mob}"> a form field to a name property in the model.
<h3 th:each="er : ${#fields.errors('mob')}" th:text="${er}"></h3> Commented [PS33]: #fields object is used to access form-
related information, including form field errors, during form
<label for="name">salary</label> processing and validation.
<input type="text" th:field="*{salary}">
<h3 th:each="er : ${#fields.errors('salary')}" th:text="${er}"></h3> Commented [PS34]: When a form is submitted and
<button type="submit" class="btn btn-primary">save</button> validation fails on the server side, the controller or service
</form> handling the form submission can add validation errors to
</div> the BindingResult object. Thymeleaf, in turn, provides an
</body> easy way to access these errors through the #fields object in
</html> the template.
#fields.errors handle form field errors and display error
• ${emp} is a model attribute (typically passed to the template from the controller) that contains an object representing an employee with a salary property. messages.
• th:object="${emp}" sets the context object for the form, so all form fields within the form will be bound to properties of the employee object.
• th:field="*{salary}" is used to bind the <input> field to the salary property of the employee object. Thymeleaf will automatically generate the appropriate
name, id, and value attributes for the input field based on the property name.
P a g e 14 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT
P a g e 15 | 15